我的JSON解析不起作用

时间:2018-04-25 15:29:59

标签: json swift

我有一个API提供的JSON。代码如下:

DispatchQueue.main.async {
    let responseJSON = try? JSONSerialization.jsonObject(with: data, options:.allowFragments) as! [String:Any]
    let values = responseJSON!["feeds"] as? [[String: Any]] ?? []
    print("JSON")
    print(responseJSON)
    print("Feeds")
    print (values)
    for value in values {
        if let temp=value["field1"] as? Float {
            self.temperatures.append(temp)
            print(temp)
        }
    }
}

但值的结果如下:

[["field1": 12.5004340278, "entry_id": 1, "created_at": 2018-03-10T16:02:41Z], 
["field1": 12.5004340278, "entry_id": 2, "created_at": 2018-03-10T16:03:41Z], 
["field1": 12.5004340278, "entry_id": 3, "created_at": 2018-03-10T16:03:56Z], 
["field1": 11.6866319444, "entry_id": 4, "created_at": 2018-03-10T16:06:07Z], 
["field1": 12.2291666667, "entry_id": 5, "created_at": 2018-03-10T16:06:23Z]]

之后,它不打印我的临时工。知道为什么吗?谢谢!

仅供参考,这就是JSON的样子:

{
    "feeds": [{
        "created_at": "2018-03-10T16:02:41Z",
        "entry_id": 1,
        "field1": "12.5004340278"
    }, {
        "created_at": "2018-03-10T16:03:41Z",
        "entry_id": 2,
        "field1": "12.5004340278"
    }, {
        "created_at": "2018-03-10T16:03:56Z",
        "entry_id": 3,
        "field1": "12.5004340278"
    }, {
        "created_at": "2018-03-10T16:06:07Z",
        "entry_id": 4,
        "field1": "11.6866319444"
    }, {
        "created_at": "2018-03-10T16:06:23Z",
        "entry_id": 5,
        "field1": "12.2291666667"
    }]
}

1 个答案:

答案 0 :(得分:0)

温度是JSON中的字符串,因此您必须将字符串转换为Double

if let temp=value["field1"] as? String, let temperature = Double(temp) {
    ...
}