iosswiftdecodablejsonparser

Decode using JSONDecoder Swift


What is the data model corresponding to the below json?

{ 
   dog:
   {
      type: "dog",
      logoLocation: "url1"
   },
   pitbull: 
   {
       type: "pitbull",
       logoLocation: "url2"
    }
}

This is a dictionary of dictionaries So I tried,

class PhotosCollectionModel: Codable {
    var photoDictionary: Dictionary<String, PhotoModel>?
}

class PhotoModel: Codable {
    var type: String?
    var logoLocation: String?
}

But it is not working. Any help please?


Solution

  • You need

    struct Root: Codable {
        let dog, pitbull: Dog
    }
    
    struct Dog: Codable {
        let type, logoLocation: String  // or let logoLocation:URL
    }
    

    Correct json

    {
        "dog":
        {
            "type": "dog",
            "logoLocation": "url1"
        },
        "pitbull":
        {
            "type": "pitbull",
            "logoLocation": "url2"
        }
    }
    

    for dynamic

    just use [String:Dog] in Decoder

        do {
    
            let res  = try JSONDecoder().decode([String:Dog].self,from:data)
        }
        catch {
    
            print(error)
        }