如何在Swift 4中使用整数作为键解码JSON? [英] How to decode JSON with integer as key in Swift 4?

查看:126
本文介绍了如何在Swift 4中使用整数作为键解码JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如您所见,右侧数据具有诸如"7","8"等的键. 现在我知道这些不是完全整数",因为它们是String中的数字. 但是,当我解码它们时,我需要使用该键名作为变量名. 但是,我们不能将数字用作变量名.

As you can see, the right hand data has keys like "7", "8" etc... Now I know that these are not quite "integers" because they are numbers in String. However, when I decode them, I need to use that key name as the variable name. But, we cannot have number as a variable name.

在这种情况下我该怎么办?我该如何解码?

What should I do in this case? How can I decode this?

重新创建数据集,使其没有数字作为键是否更好?但是,当人们无法控制数据集时,他们会怎么做?

Is it just better to re-create the dataset so that it does not have the number as the key? But then, what do people do when they do not have control the dataset?

整个代码太长且无关紧要,所以我只是截屏了. 如果需要,您可以在此处查看JSON数据 https://api.myjson.com/bins/11r19i

The entire code is too long and irrelevant so I just took a screenshot. If you want, you can see the JSON data here https://api.myjson.com/bins/11r19i

推荐答案

您可以使用 来实现.

struct bus: Codable {
    var one: String?
    var two: String?
    var three: String?
    enum CodingKeys: String, CodingKey {
        case one  = "1"
        case two = "2"
        case three = "3"
    }
}

它将解码每个case中的那些密钥,您现在应该可以识别出来.

it will decode those keys inside each case, you should be able to recognize now.

这篇关于如何在Swift 4中使用整数作为键解码JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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