voximdo
voximdo

Reputation: 63

Parsing strange JSON - swift

I am starting my adventure with Swift and iOS developing. And I am fighting for few hours with parsing this json result:

[
[
    {
        "id": 289462,
        "value": "24.80",
        "taken_at": "2017-07-02 19:03:03",
        "key": "temperature"
    }
],
[
    {
        "id": 289463,
        "value": "52.20",
        "taken_at": "2017-07-02 19:03:05",
        "key": "humidity"
    }
]
]

It hasn't got this "name" before all of results, and I don't know, maybe this is causing errors? And below is my function to get data:

    func get_data()
{
    let headers = [
        "content-type": "application/x-www-form-urlencoded",
        "cache-control": "no-cache",
        "postman-token": "fd20c3c4-650e-743c-3066-597de91f3873"
    ]

    let postData = NSMutableData(data: "auth_key=32fd26f62677e7aa56027d9c228e1e9d6d96abc5d10f547dcb66e2a2f6ed13".data(using: String.Encoding.utf8)!)

    let request = NSMutableURLRequest(url: NSURL(string: "http://192.168.0.22/last")! as URL,
                                      cachePolicy: .useProtocolCachePolicy,
                                      timeoutInterval: 10.0)
    request.httpMethod = "POST"
    request.allHTTPHeaderFields = headers
    request.httpBody = postData as Data

    let session = URLSession.shared
    let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
        if (error != nil) {
          //  print(error)
        } else {
            //let httpResponse = response as? HTTPURLResponse

            var keys = [String]()

            do {
                if let data = data,
                    let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
                       let mes = json[""] as? [[String: Any]] {
                    for me in mes {
                        if let name = me["key"] as? String {
                            keys.append(name)
                        }
                    }
                }
            } catch {
                print("Error deserializing JSON: \(error)")
            }  
            print(keys)        
        }
    })

    dataTask.resume()
}

I've tried several codes from different sites which I googled and still array is remaining empty :(

Upvotes: 0

Views: 120

Answers (1)

vadian
vadian

Reputation: 285220

You're right the JSON is strange, the root object is [[Any]]. You can get the key values with

if let json = try JSONSerialization.jsonObject(with: data) as? [[Any]] {
    for item in json {
        if let firstItem = item.first as? [String:Any], let key = firstItem["key"] as? String {
            keys.append(key)
        }
    }
}

However if the JSON was in much more suitable format

[
    {
        "id": 289462,
        "value": "24.80",
        "taken_at": "2017-07-02 19:03:03",
        "key": "temperature"
    },
    {
        "id": 289463,
        "value": "52.20",
        "taken_at": "2017-07-02 19:03:05",
        "key": "humidity"
    }
]

you could reduce the code to

if let json = try JSONSerialization.jsonObject(with: data) as? [[String:Any]] {
    keys = json.flatMap { $0["key"] as? String }
}

Upvotes: 2

Related Questions