Swift 3 的 JSON 序列化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39520471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSONSerialization with Swift 3
提问by Frederic
I am having a bear of a time understanding simple JSON serialization principles with Swift 3. Can I please get some help with decoding JSON from a website into an array so I can access it as jsonResult["team1"]["a"]etc? Here is relevant code:
我花了一段时间来理解使用 Swift 3 的简单 JSON 序列化原则。我能否获得一些帮助,将 JSON 从网站解码为数组,以便我可以访问它jsonResult["team1"]["a"]等?这是相关代码:
let httprequest = URLSession.shared.dataTask(with: myurl){ (data, response, error) in
self.label.text = "RESULT"
if error != nil {
print(error)
} else {
if let urlContent = data {
do {
let jsonResult = try JSONSerialization.jsonObject(with: urlContent, options:
JSONSerialization.ReadingOptions.mutableContainers)
print(jsonResult) //this part works fine
print(jsonResult["team1"])
} catch {
print("JSON Processing Failed")
}
}
}
}
httprequest.resume()
the incoming JSON is:
传入的 JSON 是:
{
team1 = {
a = 1;
b = 2;
c = red;
};
team2 = {
a = 1;
b = 2;
c = yellow;
};
team3 = {
a = 1;
b = 2;
c = green;
};
}
Thanks
谢谢
回答by OOPer
In Swift 3, the return type of JSONSerialization.jsonObject(with:options:)has become Any.
在 Swift 3 中, 的返回类型JSONSerialization.jsonObject(with:options:)变成了Any.
(You can check it in the Quick Help pane of your Xcode, with pointing on jsonResult.)
(您可以在 Xcode 的 Quick Help 窗格中查看它,并指向jsonResult。)
And you cannot call any methods or subscripts for the variable typed as Any. You need explicit type conversion to work with Any.
并且您不能为类型为 的变量调用任何方法或下标Any。您需要显式类型转换才能使用Any.
if let jsonResult = jsonResult as? [String: Any] {
print(jsonResult["team1"])
}
And the default Element type of NSArray, the default Value type of NSDictionaryhave also become Any. (All these things are simply called as "id-as-Any", SE-0116.)
而默认的 Element 类型NSArray,默认的 Value 类型NSDictionary也都变成了Any。(所有这些东西都简称为“id-as-Any”,SE-0116。)
So, if you want go deeper into you JSON structure, you may need some other explicit type conversion.
所以,如果你想更深入地了解你的 JSON 结构,你可能需要一些其他的显式类型转换。
if let team1 = jsonResult["team1"] as? [String: Any] {
print(team1["a"])
print(team1["b"])
print(team1["c"])
}
回答by Frederic
Thank you. The information from OOPer helped. But, what really helped was reformatting my json:
谢谢你。来自 OOPer 的信息有所帮助。但是,真正有帮助的是重新格式化我的 json:
{ "teams": [ { "a": 1, "b": 2, "c": "red" }, { "a": 1, "b": 2, "c": "yellow" }, { "a": 1, "b": 2, "c": "green" } ] }

