为什么使用Codable解码json nil?

时间:2018-12-17 19:57:36

标签: json swift

我正在使用最新版本的Swift和xcode 10.1。我可以很好地对对象进行json编码,但是将json字符串解码回对象会产生nil。

这是从黑客正午教程中获得的,该教程的源代码也显示为nil。

这是示例对象:

class Car: NSObject, Codable {
    var name: String = ""
    var companyURL: URL? = nil
    var yearOfManufacture: Int = 0
    var isNew:Bool = true
    var otherDetailsData: [String:String]? = nil
    var carType: CarType = .Unknown
    var carSize: CarSize = CarSize(height: 0, length: 0)
}
struct CarSize: Codable {
    var height: Double
    var length: Double
}

enum CarType: String, Codable {
    case Unknown
    case SUV
    case Sedan
}

//here is sample json
        let jsonString = """
                        {
                            "name":"City ZX",
                            "isNew":true,
                            "yearOfManufacture":2018,
                            "companyURL":"www.honda.com",
                            "carType":"Sedan",
                            "carSize":{
                                       "height":200,
                                       "height":100
                                   },
                            "otherDetailsData":{
                                       "color":"Red",
                                       "fuelType":"Petrol"
                                   },
                        }
                        """
//here is where i attempt to create the object from the json string:
        if let jsonData = jsonString.data(using: .utf8)
        {
            //And here you get the Car object back
            let carTest = try? JSONDecoder().decode(Car.self, from: jsonData)
            print("carObject currently printing nil ", carTest)
        }

1 个答案:

答案 0 :(得分:2)

您的CarSize结构具有属性heightlength,但是在您的jsonString中,您仅两次声明了height,因此您忘记了{{1} }也是解码所必需的。

您可能想在length中使用length而不是第二height

jsonString

或者(如果您的汽车不是摩天大楼)

"carSize":{                             
    "height":200,
    "length":100
}