Swift JSON序列化类型不匹配 [英] Swift JSON Serialization typeMismatch

查看:330
本文介绍了Swift JSON序列化类型不匹配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前在如何使用可解码"方面苦苦挣扎.我已经对出现的错误做了一些谷歌搜索,但我仍然相信构造结构的方式不正确,但对我来说似乎很有意义.

Currently struggling how to use Decodable. I've done some googling to the errors I'm getting but I still believe that the way i'm structuring the structs isn't correct but it seems to make sense to me.

我也尝试过使用可选项

在我最后发布的错误中,我对Double类型的引用感到困惑.由于我没有任何类型或任何int值,因此他的响应使用了double.

In the error that I've posted at the end, I'm confused about the reference to the Double type. As I don't have any type or anything int he response that uses a double.

(我还能够使用将数据转换为字典的旧的swift快速方法来序列化json响应-[String:Any].但我想使用现代/更新的方法.)

(I'm also able to serialize the json reponse using the old swift method of casting the data as dictionaries - [String : Any]. But I'd like to use the modern/updated approach.)

JSON响应

    {"NEWS":
  [
    {
      "DATE":"2018-10-13T03:56:06+1000",
      "SOURCE":"smh.com.au",
      "BLURB":"Assistant Treasurer Stuart Robert says he has repaid $37,975 of \"excess usage charges\" in home internet bills footed by taxpayers.",
      "ID":102347,
      "TITLE":"Stuart Robert pays back $38,000 in excessive home internet charges"
    },
    {
      "DATE":"2018-10-12T18:00:38+1000",
      "SOURCE":"itwire.com",
      "BLURB":"The CVC costs set by the NBN Co make it very difficult for ISPs to offer gigabit connections to more than a select band of customers who are willing to sign up in numbers and pay slightly more than other speed tiers, according to one ISP who caters to this type of consumer.",
      "ID":102343,
      "TITLE":"NBN gigabit connections will remain mostly a pipe dream"},
    {
      "DATE":"2018-10-12T09:48:43+1000",
      "SOURCE":"computerworld.com.au",
      "BLURB":"The Department of Home Affairs has rejects calls to include independent judicial oversight of the decision to issue Technical Assistance Notices and Technical Capability Notices as part of proposed legislation intended to tackle police agencies’ inability to access encrypted communications services.",
      "ID":102342,
      "TITLE":"Home Affairs rejects calls for additional safeguards in ‘spyware’ law"
    },
    {
    "DATE":"2018-10-11T12:16:05+1000",
    "SOURCE":"itnews.com.au",
    "BLURB":"NBN Co is hoping to "speed up" building works on the fibre-to-the-curb (FTTC) portion of its network as it tries to make up lost ground.",
    "ID":102334,
    "TITLE":"NBN Co says fibre-to-the-curb build is more complex that it hoped"
    },
  ]
}

CODE

struct Root: Decodable {
    let news: [News]?

    enum CodingKeys: String, CodingKey {
        case news = "NEWS"
    }

}

struct News: Decodable {
    let date: Date
    let source, blurb: String
    let id: Int
    let title: String

    enum CodingKeys: String, CodingKey {
        case date = "DATE"
        case source = "SOURCE"
        case blurb = "BLURB"
        case id = "ID"
        case title = "TITLE"
    }
}

序列化

URLSession.shared.dataTask(with: url) { (data, response, err) in  
guard let dataStr = data else {
            return
        }
do {
    let root = try JSONDecoder().decode(Root.self, from: dataStr) //error is caught here
    guard let r = root else { return }
    print(r.news)
} catch let err {
    print("JSON Error - \(err)")
}
}.resume()

错误

错误序列化json typeMismatch(Swift.Double,Swift.DecodingError.Context(codingPath:[CodingKeys(stringValue:"NEWS",intValue:nil),_JSONKey(stringValue:"Index 0",intValue:0),CodingKeys( stringValue:"DATE",intValue:nil)],debugDescription:预期对Double进行解码,但找到了一个字符串/数据.",底层错误:nil)))

error serializing json typeMismatch(Swift.Double, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "NEWS", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0), CodingKeys(stringValue: "DATE", intValue: nil)], debugDescription: "Expected to decode Double but found a string/data instead.", underlyingError: nil))

推荐答案

这是因为Date的默认编码策略是double(自纪元以来的秒数).您可以将默认策略更改为iso8061或任何自定义设置.例如,您可以在解码器中设置日期格式器,如下所示:

This is because the default coding strategy for Date is double (seconds since epoch). You can change the default strategy to iso8061 or anything custom. For example, you can set the date formatter in your decoder like so:

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601

这篇关于Swift JSON序列化类型不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆