Search code examples
jsonswiftstructure

JSON object inside JSON object Swift


This is my JSON file.

{
    "id": 3498,
    "name": “Fetcher”,
    "description": “BlaBlaBla”,
    "released": "1993-11-11",
        "platforms": [
        {
            "platform": {
                "name": “Anaconda”,
            }
         },
         {
            "platform": {
                "name": “Cobra”,
            },
        }],
}

I have the following structure:

struct Markers: Codable {
   var id : Int?
   var name : String?
   var description : String?
   var released : String?
   var platforms : [Platforms]? ///If I comment this it works fine, otherwise it won't 
}

struct Platforms: Codable {
   var platform : [Platform]?
}

struct Platform: Codable {
   var name : String?
}

And I cannot catch the data if I use platforms in structure. If i comment the platforms in Markers structure I will get everything in data response, but with platforms it prints "Still doesn't work"

   do{
      let fetData = try JSONDecoder().decode(Markers.self, from:data)
      debugPrint(fetData)
     }
   catch{
       print("Still doesn't work")
    }

Solution

  • Replace

    var platform : [Platform]?
    

    with

    var platform : Platform?
    

    platform is an object not an array