json - Swift 4 序列化 json 时出错 typeMismatch

标签 json swift

我正在尝试将数据从静态 JSON 文件解析到我的实体,但出现以下错误:序列化 json typeMismatch 时出错

这个想法是创建一个公式收集应用程序。每次应用程序启动时都应通过加载 JSON 来加载公式集合。这样可以更轻松地更新公式列表。

我猜 JSON 解释了预期的数据结构。

我的 JSON:

[
    {
        "category_name": "Wasserbau",
        "icon": "wave",
        "formula_list": [
            {
                "formula_name": "Formel 1",
                "formula_description": "Demo Formel für Testat",
                "formula": "x=y/z",
                "favorite": false
            },
            {
                "formula_name": "Formel 2",
                "formula_description": "Demo Formel für Testat",
                "formula": "x=y/z",
                "favorite": false
            }
        ]
    },
    {
        "category_name": "Strassenbau",
        "icon": "wave",
        "formula_list": [
            {
                "formula_name": "Formel 3",
                "formula_description": "Demo Formel für Testat",
                "formula": "x=y/z",
                "favorite": false
            },
            {
                "formula_name": "Formel 4",
                "formula_description": "Demo Formel für Testat",
                "formula": "x=y/z",
                "favorite": false
            }
        ]
    },
    {
        "category_name": "Hochbau",
        "icon": "wave",
        "formula_list": [
            {
                "formula_name": "Formel 5",
                "formula_description": "Demo Formel für Testat",
                "formula": "x=y/z",
                "favorite": false
            },
            {
                "formula_name": "Formel 6",
                "formula_description": "Demo Formel für Testat",
                "formula": "x=y/z",
                "favorite": false
            }
        ]
    }
]

我尝试解析 JSON 的函数:

 func loadCategoryJSONData() {
        let jsonUrlString = "https://joshuahemmings.ch/data.json"

        guard let url = URL(string: jsonUrlString) else {return} //
        URLSession.shared.dataTask(with: url) { (data, response, err) in
            guard let data = data else {return}
            print("JSON Response: ")
            print(data)
            do {
                let categoryJSONData =  try JSONDecoder().decode(CategoryList.self, from: data)
                for category in categoryJSONData.data {
                    print(category.categoryName)
                }
            } catch let jsonErr {
                print("Error serializing json", jsonErr)
            }
            }.resume()
    }

还有我的实体:

struct CategoryList: Decodable {
        let data: [Category]
    }

    struct Formula: Codable {
        let formulaName : String
        let formulaDescription : String
        let formula : String
        let favorite: Bool

        enum CodingKeys: String, CodingKey {
            case formulaName = "formula_name"
            case formulaDescription = "formula_description"
            case formula
            case favorite
        }
        init(_ dictionary: [String: Any]) {
            self.formulaName = dictionary["formulaName"] as? String ?? ""
            self.formulaDescription = dictionary["formulaDescription"] as? String ?? ""
            self.formula = dictionary["formula"] as? String ?? ""
            self.favorite = dictionary["favorite"] as? Bool ?? false
        }
    }

    struct Category: Codable {
        let categoryName: String
        let icon: String
        let formulaList: [Formula]

        enum CodingKeys: String, CodingKey {
            case categoryName = "category_name"
            case icon = "icon"
            case formulaList = "formula_list"
        }

        init(_ dictionary: [String: Any]) {
            self.categoryName = dictionary["categoryName"] as? String ?? ""
            self.icon = dictionary["icon"] as? String ?? ""
            self.formulaList = dictionary["formulaList"] as? [Formula] ?? []
        }
    }

最佳答案

您的主要问题在于声明类型来解析此 JSON

这里没有CategoryList,它会是这样的:

{
    "data": [ … <Category JSON> … ]
}

这里只有 [Category],就像 JSON 根是 Array([]),而不是 Object({})。

所以而不是

try decoder.decode(CategoryList.self, from: data)

你应该这样做

try decoder.decode([Category].self, from: data)
<小时/>

此外,如果您的编码键与 JSON 中的键几乎相同,但不是蛇形格式,则不应为您的类型声明自定义 CodingKey。正确使用.keyDecodingStrategy相反。

struct Formula: Codable {
    let formulaName: String
    let formulaDescription: String
    let formula: String
    let favorite: Bool
}

struct Category: Codable {
    let categoryName: String
    let icon: String
    let formulaList: [Formula]
}

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let categoryJSONData =  try decoder.decode([Category].self, from: data)

关于json - Swift 4 序列化 json 时出错 typeMismatch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53516144/

相关文章:

android - 改造 2.0 + RxJava + 错误 JSON 正文

java - java boolean 读取方法的命名策略

ios - 有没有使用 iPhone X ARKit 创建人脸识别和检测应用程序的方法?

ios - UIAlertAction 没有初始化程序(标题、样式、处理程序)

swift - 如何在 MacOS 上使用 Swift 检查文件在 Finder 中是否具有红色标签?

ios - 如何跟踪 Sprite Kit 中的动画

java - XMLHttpRequest 返回 PHP 代码,而不是 PHP 输出

python - 使用 json_modify.py 更改 JSON 键名称

javascript - 如何使用发布请求打开新选项卡?

ios - 在 iOS (Swift) 中使用后台位置更新的最佳方式