简体   繁体   English

使用 Alamofire 解析 Swift 中的 JSON

[英]Parsing JSON in Swift with Alamofire

I'm having trouble trying to figure out how to return only one part of my JSON data using Swift 4.我无法弄清楚如何使用 Swift 4 仅返回我的 JSON 数据的一部分。

This is the JSON I need to parse:这是我需要解析的 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"
}

So far I am able to return all of the "tags" array, shown below.到目前为止,我能够返回所有“标签”数组,如下所示。 However, I just need to return only the "smoothedPosition" data.但是,我只需要返回“smoothedPosition”数据。

    func newTest() {
        Alamofire.request(url).responseJSON { (response) in

            if let newjson = response.result.value as! [String: Any]? {
                print(newjson["tags"] as! NSArray)
            }
        }

    }

Would alamofire be a good way to get the result I want? alamofire 会是获得我想要的结果的好方法吗? I previously tried with the Codable method but because there are many different parts to my JSON, I found it confusing to just get the part I need.我之前尝试过使用 Codable 方法,但是因为我的 JSON 有许多不同的部分,我发现只获得我需要的部分会让人感到困惑。 If anyone could give me some advice on the best way to go about this, I would appreciate it.如果有人能给我一些关于 go 的最佳方式的建议,我将不胜感激。

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

To get smoothedPosition you need to parse more.要获得smoothedPosition ,您需要进行更多解析。 tags gives you an array of dictionaries , so you need to loop array and get each dictionary inside tags array . tags为您提供了一个array of dictionaries ,因此您需要循环数组并在tags array中获取每个字典。 Then finally you can get your smoothedPosition 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)
                }
            }
        }
    }
}
  • Also you should read more about codables to parse nested data and learn about optional binding and chaining to prevent crashes when you force (!) something which could be nil at some point.此外,您应该阅读更多关于codablesparse nested data并了解optional binding and chaining以防止在您force (!)某些可能在某些时候为零的东西时崩溃。

  • You can use this site to check the possible Codable structure as per your response: https://app.quicktype.io/您可以使用此站点根据您的回复检查可能的Codable结构: https://app.quicktype.io/

It is a good option to create a custom Codable struct or class for the JSON response.为 JSON 响应创建自定义Codable结构或 class 是一个不错的选择。 You may only implement as member variable which you want to reach.您只能实现为您想要达到的成员变量。

struct CustomResponse: Codable {
    let tags: [Tag]
}

struct Tag: Codable {
    let smoothedPosition: Position
}

struct Position: Codable {
   let x: Float
   let y: Float
   let z: Float
}

Then然后

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

Also you can parse deeper manually your JSON response as stated in the other answers.您还可以手动更深入地解析您的 JSON 响应,如其他答案中所述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM