-5

Can anyone tell me how to parse this JSON reponse? I need to extract "last name" from the services.

{  
   "Entity":{  
      "ID":1,
      "UserTypeID":1,
      "Code":"lPEq",
      "Services":[  
         {  
            "ID":118,
            "Code":"1",
            "Parent_ID":null,
            "Name":"Alex",
            "lastName":"John"
         },
         {  
            "ID":119,
            "Code":"2",
            "Parent_ID":null,
            "Name":"Christy",
            "lastName":"Noel"
         }
      ]
   }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • Show us what you have tried. – Rob Jul 07 '17 at 15:02
  • 1
    Please make some minimal attempt to search on something that has been [asked many, many, many times before](https://stackoverflow.com/search?q=%5Bswift%5D+parse+json+how). – rmaddy Jul 07 '17 at 16:16

1 Answers1

0

Here's how you can do it. Don't forget to handle unwrap

let str = "{ \"Entity\":{ \"ID\":1, \"UserTypeID\":1, \"Code\":\"lPEq\", \"Services\":[ { \"ID\":118, \"Code\":\"1\", \"Parent_ID\":null, \"Name\":\"Alex\", \"lastName\":\"John\" }, { \"ID\":119, \"Code\":\"2\", \"Parent_ID\":null, \"Name\":\"Christy\", \"lastName\":\"Noel\" } ] } }"

let data = str.data(using: .utf8)

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

    let entityDic = json?["Entity"] as? [String: Any]
    let servicesDic = entityDic?["Services"] as? [Any]
    let firstPerson = servicesDic?[0] as? [String: Any]
    dump(firstPerson?["lastName"])
}catch let error{

}
Fangming
  • 24,551
  • 6
  • 100
  • 90