用Alamofire在Swift中解析JSON



我很难弄清楚如何使用Swift 4只返回JSON数据的一部分。

这是我需要解析的JSON:

{
"code": 0,
"responseTS": 1571969400172,
"message": "TagPosition",
"version": "2.1",
"command": "http://123.456.7.89:8080/tag=a4da22e02925",
"tags": [
{
"smoothedPosition": [
-0.58,
-3.57,
0.2
],
"color": "#FF0000",
"positionAccuracy": 0.07,
"smoothedPositionAccuracy": 0.07,
"zones": [],
"coordinateSystemId": "687eba45-7af4-4b7d-96ed-df709ec1ced1",
"areaId": "987537ae-42f3-4bb5-8d0c-79fba8752ef4",
"coordinateSystemName": "CoordSys001",
"covarianceMatrix": [
0.04,
0.01,
0.01,
0.05
],
"areaName": "area",
"name": null,
"positionTS": 1571969399065,
"id": "a4da22e02925",
"position": [
-0.58,
-3.57,
0.2
]
}
],
"status": "Ok"
}

到目前为止,我能够返回所有的"标签"数组,如下所示。然而,我只需要返回"smoothedPosition"数据。

func newTest() {
Alamofire.request(url).responseJSON { (response) in
if let newjson = response.result.value as! [String: Any]? {
print(newjson["tags"] as! NSArray)
}
}
}

发烧是得到我想要的结果的好方法吗?我以前尝试过Codable方法,但由于JSON有很多不同的部分,我发现只得到我需要的部分很令人困惑。如果有人能给我一些关于最好的方法的建议,我将不胜感激

Better not to use NS classes with Swift wherever possible. So instead of NSArray use Array.

要获得smoothedPosition,您需要解析更多内容。tags为您提供了一个array of dictionaries,因此您需要循环数组并在tags array中获取每个字典。然后你终于可以得到你的smoothedPosition数组了。

func newTest() {
Alamofire.request(url).responseJSON { (response) in
if let newjson = response.result.value as? [String: Any], if let tagArray = newjson["tags"] as? [[String: Any]] {
for object in tagArray {
if let smoothedPosition = object["smoothedPosition"] as? [Double] {
print(smoothedPosition)
}
}
}
}
}
  • 此外,您还应该阅读更多关于codablesparse nested data的内容,并了解optional binding and chaining,以防止在force (!)时发生崩溃——某些情况下可能为零。

  • 您可以使用此网站根据您的回复检查可能的Codable结构:https://app.quicktype.io/

为JSON响应创建自定义Codable结构或类是一个不错的选项。您只能实现为要访问的成员变量。

struct CustomResponse: Codable {
let tags: [Tag]
}
struct Tag: Codable {
let smoothedPosition: Position
}
struct Position: Codable {
let x: Float
let y: Float
let z: Float
}

然后

Alamofire.request(url).responseJSON { (response as? CustomResponse) in
guard let response = response else { return }
print(response.tags.smoothedPosition)
}

此外,您还可以像其他答案中所述的那样,更深入地手动解析JSON响应。

最新更新