首页 > 解决方案 > json 解析不正确

问题描述

所以我尝试解析一个 json 文件,当我按照语法解析它时,它给了我一个错误,无法将字符串更改为字典数组,但是当我解决问题时,它会生成nil. 谁能给个意见

func jsonFour() {
    let string = "[{\"address\": 7023000630,\"reportStatus\": \"Retrieved\",\"currentLocation\": {\"latitude\": 29.8529, \"longitude\": 73.99332,\"timestamp\": \"2019-01-07T16:35:25.079+05:30\"} }, {\"address\": 7290098339, \"reportStatus\": \"Retrieved\", \"currentLocation\": {\"latitude\": 21.628569, \"longitude\": 72.996956,\"timestamp\": \"2019-01-07T16:35:25.079+05:30\" } } ]"

    let data = string.data(using: .utf8)!
    do {
        if let jsonArray = try JSONSerialization.jsonObject(with: data, options : JSONSerialization.ReadingOptions.mutableContainers) as? [[ String : Any ]]
        {
            print(jsonArray) // use the json here
            let address = jsonArray["address"] as! [[String:Any]]
            if let timestamp = address["timestamp"] as? [String]{print(timestamp)}
        } else {
            print("bad json")
        }
    } catch let error as NSError {
        print(error)
    }

}

当我从 中删除双括号时"String : Any",它运行良好,但没有给出任何值,但nil.

当我以这种方式继续时,它会跳过 if 语句并只打印"bad json".

我在这里做错了什么?

标签: iosjsonswiftapi

解决方案


既然有Codable,我强烈建议您使用它而不是JSONSerialization.

因此,首先声明您的结构以与您的 JSON 结构匹配

struct Model: Codable {
    var address: Int
    var reportStatus: String
    var currentLocation: Location
}

struct Location: Codable {
    var latitude, longitude: Double
    var timestamp: String
}

现在只需使用解码您的 JSONJSONDecoder

do {
    let data = string.data(using: .utf8)!
    let models = try JSONDecoder().decode([Model].self, from: data)
} catch {
    print(error)
}

...现在modelsModel对象数组,您可以使用它。


推荐阅读