我正在尝试获取JSON响应并将结果存储在变量中.我已经在Swift的早期版本中使用了此代码的版本,直到GM版本的Xcode 8发布.我看了一下StackOverflow上的一些类似的帖子:Swift 2解析JSON - 无法下标Swift 3中的'AnyObject'和JSON解析类型的值.
但是,似乎那里传达的想法并不适用于这种情况.
如何在Swift 3中正确解析JSON响应?在Swift 3中读取JSON的方式有什么变化吗?
以下是有问题的代码(可以在游乐场中运行):
import Cocoa
let url = "https://api.forecast.io/forecast/apiKey/37.5673776,122.048951"
if let url = NSURL(string: url) {
if let data = try? Data(contentsOf: url as URL) {
do {
let parsedData = try JSONSerialization.jsonObject(with: data as Data, options: .allowFragments)
//Store response in NSDictionary for easy access
let dict = parsedData as? NSDictionary
let currentConditions = "\(dict!["currently"]!)"
//This produces an error, Type 'Any' has no subscript members …Run Code Online (Sandbox Code Playgroud) 有没有人能够找到一种方法来解析Swift 3中的JSON文件?我已经能够返回数据但是在将数据分解为特定字段时我没有成功.我会发布示例代码,但我已经通过这么多不同的方法失败了,并没有保存任何.我要解析的基本格式是这样的.提前致谢.
{
"Language": {
"Field":[
{
"Number":"976",
"Name":"Test"
},
{
"Number":"977",
"Name":"Test"
}
]
}
}
Run Code Online (Sandbox Code Playgroud) 我有这个我希望在Swift 3中使用的json数据.我正在学习Swift并构建一个非常基本的应用程序,它显示来自JSON的tableUIView中的项目列表.
{
"expertPainPanels" : [
{
"name": "User A",
"organization": "Company A"
},
{
"name": "User B",
"organization": "Company B"
}
]
}
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用Swift 3获取此数据.
if (statusCode == 200) {
do{
let json = try? JSONSerialization.jsonObject(with: data!, options:.allowFragments) // [[String:AnyObject]]
/*
If I do this:
let json = try? JSONSerialization.jsonObject(with: data!, options:.allowFragments) as! [String:Any]
if let experts = json?["expertPainPanels"] as! [String: Any] {
I get "Initializer for conditional binding must have Optional type, not '[String: Any]'"
*/
// Type …Run Code Online (Sandbox Code Playgroud)