ios - 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"
.
我在这里做错了什么?
解决方案
既然有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)
}
...现在models
是Model
对象数组,您可以使用它。
推荐阅读
- java - 为什么要在对象数组类内部创建对象数组?
- opengl - 有选择地绘制到着色器中的某些输出
- laravel - laravel 关系 belongsTo 和方法 with
- reinforcement-learning - Q 学习和神经网络的问题
- excel - 循环中的 If-Else-Statement
- python - 如何在此 LSTM 示例代码中计算可训练参数数量为 335872?
- jquery - 阴影行切换有/没有 jquery / css 未应用于第 n 行
- mysql - MYSQL - 在 select 和 group by 中将多列显示为不同的值
- c# - 从 .net core 中的其他类库访问 automapper
- flutter - Flutter 文本在某些情况下无法正确呈现