Swift Codable需要解码Dictionary <string,any =“”>,而是找到一个字符串/数据

时间:2017-10-30 11:03:59

标签: json swift swift4 codable

我一直在使用Codable协议

这是我的JSON文件:

    {  
   "Adress":[  

   ],
   "Object":[  
      {  
         "next-date":"2017-10-30T11:00:00Z",
         "text-sample":"Some text",
         "image-path":[  
            "photo1.png",
            "photo2.png"
         ],
         "email":"john.doe@test.com",
         "id":"27"
      },
      {  
         "next-date":"2017-10-30T09:00:00Z",
         "text-sample":"Test Test",
         "image-path":[  
            "image1.png"
         ],
         "email":"name.lastename@doe.com",
         "id":"28"
      }
   ]
}

我只需要专注于Object数组,以及&#34; image-path&#34;数组可以包含0,1或2个字符串。

所以这是我的实施:

struct Result: Codable {
    let Object: [MyObject]
}

struct MyObject: Codable {

    let date: String
    let text: String
    let image: [String]
    let email: String
    let id: String

    enum CodingKeys: String, CodingKey {
        case date = "next-date"
        case text = "text-sample"
        case image = "image-path"
        case email = "email"
        case id = "id"
    }

    init() {
        self.date = ""
        self.text = ""
        self.image = []
        self.email = ""
        self.id = ""
    }
}

在以这种方式请求和获取JSON数据后,我从我的服务类中调用它:

if let data = response.data {
                let decoder = JSONDecoder()
                let result = try! decoder.decode(Result, from: data)
                dump(result.Object)
            }

[String]属性

image外,其他所有工作都有效

但是它无法编译,或者我得到了一个&#34;期望解码......&#34;错误。

我应该如何处理nil / no数据场景?

1 个答案:

答案 0 :(得分:5)

我对你的MyObject struct进行了一些小改动,即

1。将所有properties标记为optionals

2。已移除init()(我认为此处不需要init()。)

3。Result.self方法中使用Result代替decoder.decode(...)

struct MyObject: Codable
{
    let date: String?
    let text: String?
    let image: [String]?
    let email: String?
    let id: String?

    enum CodingKeys: String, CodingKey
    {
        case date = "next-date"
        case text = "text-sample"
        case image = "image-path"
        case email = "email"
        case id = "id"
    }
}

为了测试上述内容,我使用了以下代码,它运行正常。

    let jsonString = """
        {"Adress": [],
        "Object": [{"next-date": "2017-10-30T11:00:00Z",
        "text-sample": "Some text",
        "image-path": ["photo1.png", "photo2.png"],
        "email": "john.doe@test.com",
        "id": "27"},
      {"next-date": "2017-10-30T09:00:00Z",
       "text-sample": "Test Test",
       "image-path": ["image1.png"],
       "email": "name.lastename@doe.com",
       "id": "28"}
       ]
        }
    """
    if let data = jsonString.data(using: .utf8)
    {
        let decoder = JSONDecoder()
        let result = try? decoder.decode(Result.self, from: data) //Use Result.self here
        print(result)
    }

这是我得到的结果值:

enter image description here