1

I'm using latest version of Swift with xcode 10.1. I'm able to encode json from an object fine but decoding a json string back to an object is producing nil.

This is from a hacker noon tutorial and the tutorial source prints nil as well.

Here is the sample object:

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)
        }
6
  • 2
    Because the decoding fails already. Don't try?, catch the error and print it. And a dictionary with two height keys is invalid anyway. Commented Dec 17, 2018 at 20:00
  • error keyNotFound(CodingKeys(stringValue: "length", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "carSize", intValue: nil)], debugDescription: "No value associated with key CodingKeys(stringValue: \"length\", intValue: nil) (\"length\").", underlyingError: nil)) Commented Dec 17, 2018 at 20:10
  • ok, thanks for error tip. now i need to figure out what is going with the keyNotFound stuff. Commented Dec 17, 2018 at 20:11
  • 1
    Read the error message and the JSON. Is there a key length in the carSize dictionary? Commented Dec 17, 2018 at 20:12
  • @vadian You are wrong, that JSON is valid even if two keys are the same. When decoded, usually the last key will be used. Commented Dec 17, 2018 at 20:15

1 Answer 1

2

Your CarSize struct has properites height and length, but in your jsonString you declared just height twice, so you forgot to length which is required for decoding too.

You probably wanted to use length instead of second height in your jsonString

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

or (if your car isn't skyscraper)

"carSize":{                             
    "height":100,
    "length":200
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.