简体   繁体   English

将JSON解析为Struct Swift 4

[英]Parsing JSON into Struct Swift 4

I am trying to parse some JSON into a struct. 我正在尝试将一些JSON解析为一个结构。 Since that seems to be the way I have seen folks do this? 既然那是我看到人们这样做的方式? The data is a Data object I just got from a URLRequest. 数据是我刚从URLRequest获得的数据对象。

Here is a sample of the JSON: 这是JSON的示例:

{
  "policies": [{
    "id": 100,
    "name": "00 Kickoff"
  }, {
    "id": 237,
    "name": "02 Install Program 01"
  }, {
    "id": 13,
    "name": "03 AV Install"
  }, {
    "id": 114,
    "name": "04 - Tag Device"
  }, {
    "id": 102,
    "name": "05 VPN Install"
  }]
}

There are many more items but this is the exact structure of the JSON. 还有很多其他项目,但这是JSON的确切结构。

So I wrote a couple of Structs thinking that will hold the data: 因此,我写了一些Structs,认为可以保存数据:

struct Policies: Codable {
    let policies: [Policy]

    private enum CodingKeys: String, CodingKey {
        case policies = "policies"
    }
}

struct Policy: Codable {
    let id: String?
    let name: String?

    private enum CodingKeys: String, CodingKey {
        case id = "id"
        case name = "name"
    }
}

Then I try and do the decode: 然后,我尝试进行解码:

do {
    let jssPolicies: Policies = try decoder.decode(Policies.self, from: data)
} catch let error as NSError {
    debugPrint("Error: \(error.description)")
    }

But then I get the error: 但是然后我得到了错误:

"Error: Error Domain=NSCocoaErrorDomain Code=4864 \"Expected to decode Array<Any> but found a dictionary instead.\" UserInfo={NSCodingPath=(\n), NSDebugDescription=Expected to decode Array<Any> but found a dictionary instead.}"

I feel like I am close? 我觉得我接近了吗? But who knows perhaps I am not. 但是谁知道我可能不是。 Any help someone can off on how to take this Data object that I get from the URL request and turn it into JSON would be helpful. 有人可以提供如何从URL请求中获取此Data对象并将其转换为JSON的任何帮助都会有所帮助。 I have looked at a few posts but since the structure of the JSON is different I am a bit stuck. 我看了几篇文章,但是由于JSON的结构不同,所以我有点受阻。

Thanks in Advance, Ed 在此先感谢,Ed

Actually with the given JSON you should get 实际上,使用给定的JSON,您应该得到

Type 'String' mismatch: Expected to decode String but found a number instead. 类型“字符串”不匹配:预期会解码String但找到了一个数字。

because the value for key id is an Int . 因为key id的值是Int Is this the real JSON? 这是真正的JSON吗?

You get the described error if you try to decode [Policies].self 如果尝试解码[Policies].self得到描述的错误。

And you can omit all CodingKeys, if they match the property names you get them for free 您可以省略所有CodingKeys,如果它们与属性名称匹配,则可以免费获得它们

struct Policies: Codable {
    let policies: [Policy]
}

struct Policy: Codable {
    let id: Int
    let name: String
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM