0

How can I JSON object inside an array in swift4? How ca I get the response for this JSON in swift4? I am printing the location but its's getting nil.

Here its my JSON data:

{
    "Details": [{
        "phone": 
        "id":
    }],
    "address": [{
       "location": "some location"
   }]
}

 do {
     let json = try JSONSerialization.jsonObject(with: data!, options: []) as! [String: AnyObject]

     let location = json["location"] as? [[String: AnyObject]]
     print(location)

 } catch {         
     print("error")       
 }

1 Answer 1

2

json["location"] doesn't exist and therefore is not an array. Location is inside the address array.

try

if let addressArray = json["address"] as? [[String: Any]] {
    let address = addressArray.first
    let location = address?["location'] as? String
    print(location)
} 

NOTES

  1. In your JSON location was missing any value i.e "location": I added a String
  2. it's better to use the Codable protocol in Swift 4
Sign up to request clarification or add additional context in comments.

4 Comments

why u wrote addressArray.first what is first?
Square bracket [] in JSON is an array/list. so addressArray is a list of addresses, .first gets the first item in the list
so i want the "phone" soo i need to call Details.second?
Yes maybe, you need to check that the second item in the list is definitely the phone number

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.