首页 > 解决方案 > 使用 JSONDecoder Swift 解码

问题描述

下面的json对应的数据模型是什么?

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

这是一本字典所以我试过了

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

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

但它不起作用。请问有什么帮助吗?

标签: iosswiftdecodablejsonparser

解决方案


你需要

struct Root: Codable {
    let dog, pitbull: Dog
}

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

正确的 json

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

对于动态

[String:Dog]在解码器中使用

    do {

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

        print(error)
    }

推荐阅读