Search code examples
iosjsonswiftalamofire

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.

This is the JSON I need to parse:

{
  "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.

    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? 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. If anyone could give me some advice on the best way to go about this, I would appreciate it.


Solution

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

    To get smoothedPosition you need to parse more. tags gives you an array of dictionaries, so you need to loop array and get each dictionary inside tags array. Then finally you can get your smoothedPosition array.

    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.

    • You can use this site to check the possible Codable structure as per your response: https://app.quicktype.io/