Home > Software design >  Getting value from JSONSerialization key Swift
Getting value from JSONSerialization key Swift

Time:04-22

I have the following JSON...

{
"id": "1000035148",
"petId": "3",
"ownerId": "1000",
"locationId": null,
"status": "Active",
“services”: [
    {
       "id": "5004",
       “data”: 1,
       “data1”: 0,
       “data2": 63,
       “data3": 0
   }
 ]
}

And I'm only trying to return the following objects...

"id": "1000035148",
"petId": "3",
"ownerId": "1000",
"locationId": null,
"status": "Active"

How can I achieve this with the following code?

session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: Error?) in
            if let data = data {
                do {
                    let jsonData = try JSONSerialization.jsonObject(with: data)
                    if let dictionary = jsonData as? [String: Any] {
                        if let nestedDictionary = dictionary["status"] as? [String: Any] {
                            for (key, value) in nestedDictionary {
                                print("Key: \(key), Value: \(value)")
                            }
                        }
                    }
                    print(jsonData)
                } catch {
                    print("Error fetching data from API: \(error.localizedDescription)")
                }
            }

When I try to parse using the nestedDictionary = dictionary I get an error and it skips over the line. I'm confused on how to get just the key value pairs I want from the response.

CodePudding user response:

Forget JSONSerialization and use Decodable with JSONDecoder:

struct DataModel: Decodable {
   let id: String
   let pedId: String?
   let ownerId: String?
   let locationId: String?
   let status: String
}
do {
    let dataModel = try JSONDecoder().decode(DataModel.self, from: data)
    print("Status: \(dataModel.status)")  
} catch ...

If you want to use JSONSerialization, note that status is not a dictionary, it's a String:

if let dictionary = jsonData as? [String: Any] {
    if let status = dictionary["status"] as? String {
        print("Status: \(status)")                           
    }
}

  • Related