0
votes

I have a JSON with keys

{  
   "yearOfManufacture":"20/9/2018",
   "carSize":8,
   "isNew":true,
   "carAssets":[  
      {  
         "color":"5761807993001",
         "nativeId":"{\"app\":\"1234/Car/Native_App\",\"web\":\" /8888/Car/Native_Car_Desktop\"}"
      }
   ]
}

I am trying to parse using Codable protocol with struct models

struct Cars: Codable {
   var yearOfManufacture: String?
   var carSize: Int = 0
   var isNew: Bool = true
   var carAssets: [CarAssests]?
}

struct CarAssests: Codable { 
   var color: String?
   var nativeId: String?
}

I am getting error like The data couldn’t be read because it isn’t in the correct format. I tried using CodingKeys with decoder container not getting the exact type of "nativeId": "{\"app\":\"1234/Car/Native_App\",\"web\":\" /8888/Car/Native_Car_Desktop\"}" not getting exact data type of this.

let decoder = JSONDecoder()
        decoder.dataDecodingStrategy = .deferredToData
        if let jsonData = jsonString.data(using: .utf8) {
            do {

                print(jsonData)
                let assets = try decoder.decode(Cars.self, from: jsonData)
                print(assets)
            } catch {
                print(error.localizedDescription)
            }
        }
1
What do you mean by "if i remove nativeId key" ? - Mihai Fratu
if i remove nativeId from JSON it is getting parsed successfully!! - salman siddiqui
nativeId is a JSON string, encoded as JSON. it wont be parsed in the same way, you will need to manually sort that one out - Scriptable
Do i need to encode complete JSON or only the key - salman siddiqui
Can you show the declaration of jsonString? Are you reading it from a file or using a multiline string literal? - Sweeper

1 Answers

0
votes

I bet you are doing something like this:

let jsonString = """
{
"yearOfManufacture": "20/9/2018",
"carSize": 8,
"isNew": true,
"carAssets": [
{
"color": "5761807993001",
"nativeId": "{\"app\":\"1234/Car/Native_App\",\"web\":\" /8888/Car/Native_Car_Desktop\"}"
}
]
}
"""

In a multiline string, both \" and " mean the character ". So you have to write \\" to get the two characters \ and ":

let jsonString = """
{
"yearOfManufacture": "20/9/2018",
"carSize": 8,
"isNew": true,
"carAssets": [
{
"color": "5761807993001",
"nativeId": "{\\"app\\":\\"1234/Car/Native_App\\",\\"web\\":\\" /8888/Car/Native_Car_Desktop\\"}"
}
]
}
"""