如何解析 json 响应 swift3?
How to parse json response swift3?
我的回复是这样的:
[
{
"Part" : {
"id" : "418502",
"uuid" : "21ec7cdb-cd2d-4b12-8a90-775762eb0f26"
},
"Category" : {
"category_name" : "Regulators",
"category_code" : "RG"
}
},
{
"Part" : {
"id" : "418502",
"uuid" : "21ec7cdb-cd2d-4b12-8a90-775762eb0f26"
},
"Category" : {
"category_name" : "Regulators",
"category_code" : "RG"
}
}
]
所以我需要解析上面的响应以获得 Part
数组和 Category
数组。在 google 中搜索后,我发现:
let resultJson = try JSONSerialization.jsonObject(with: data, options: []) as? [String : AnyObject]
print(resultJson!)
但它抛出致命错误:在展开可选值时意外发现 nil。
我是新手 swift 我不知道如何转换它。我已经在 Android 中完成了这个,所以我可以肯定地说我得到了来自服务器的以上响应。我写了一个调用 web 服务的通用函数,它适用于其他服务,所以我认为这没有问题。
如何解析我的响应以便获得 Part
数组和 Category
数组?
谢谢。
您的 JSON 结构有一个顶级数组,因此您不能将 is 作为字典进行解析。尝试这样做
let resultJson = try JSONSerialization.jsonObject(with: data, options: []) as? [Any]
dump(resultJson!)
示例代码如下所示。不要忘记处理展开的东西
let str = "[{\"Part\":{\"id\":\"418502\",\"uuid\":\"21ec7cdb-cd2d-4b12-8a90-775762eb0f26\"},\"Category\":{\"category_name\":\"Regulators\",\"category_code\":\"RG\"}},{\"Part\":{\"id\":\"418502\",\"uuid\":\"21ec7cdb-cd2d-4b12-8a90-775762eb0f26\"},\"Category\":{\"category_name\":\"Regulators\",\"category_code\":\"RG\"}}]"
let data = str.data(using: .utf8)
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [Any]
let dicInFirstElement = json?[0] as? [String: Any]
let part = dicInFirstElement?["Part"]
dump(part)
//Pass this json into the following function
}catch let error{
}
我的回复是这样的:
[
{
"Part" : {
"id" : "418502",
"uuid" : "21ec7cdb-cd2d-4b12-8a90-775762eb0f26"
},
"Category" : {
"category_name" : "Regulators",
"category_code" : "RG"
}
},
{
"Part" : {
"id" : "418502",
"uuid" : "21ec7cdb-cd2d-4b12-8a90-775762eb0f26"
},
"Category" : {
"category_name" : "Regulators",
"category_code" : "RG"
}
}
]
所以我需要解析上面的响应以获得 Part
数组和 Category
数组。在 google 中搜索后,我发现:
let resultJson = try JSONSerialization.jsonObject(with: data, options: []) as? [String : AnyObject]
print(resultJson!)
但它抛出致命错误:在展开可选值时意外发现 nil。
我是新手 swift 我不知道如何转换它。我已经在 Android 中完成了这个,所以我可以肯定地说我得到了来自服务器的以上响应。我写了一个调用 web 服务的通用函数,它适用于其他服务,所以我认为这没有问题。
如何解析我的响应以便获得 Part
数组和 Category
数组?
谢谢。
您的 JSON 结构有一个顶级数组,因此您不能将 is 作为字典进行解析。尝试这样做
let resultJson = try JSONSerialization.jsonObject(with: data, options: []) as? [Any]
dump(resultJson!)
示例代码如下所示。不要忘记处理展开的东西
let str = "[{\"Part\":{\"id\":\"418502\",\"uuid\":\"21ec7cdb-cd2d-4b12-8a90-775762eb0f26\"},\"Category\":{\"category_name\":\"Regulators\",\"category_code\":\"RG\"}},{\"Part\":{\"id\":\"418502\",\"uuid\":\"21ec7cdb-cd2d-4b12-8a90-775762eb0f26\"},\"Category\":{\"category_name\":\"Regulators\",\"category_code\":\"RG\"}}]"
let data = str.data(using: .utf8)
do{
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [Any]
let dicInFirstElement = json?[0] as? [String: Any]
let part = dicInFirstElement?["Part"]
dump(part)
//Pass this json into the following function
}catch let error{
}