-1

i need to access the two json object inside this json object and also how do i access the array in the second json object . i have tried various ways .can anybody help me with this.thanks in advance.

{
  "usr_assess_hdr": {
    "user_id": "1",
    "trainer_id": "001",
    "gender": "Female",
    "goal": "Weight Loss"
  },
  "usr_assess_dtl": "[{\"score\":\"1\",\"assess_name\":\"Treadmill\",\"assess_no\":\"1\",\"value\":\"1\"},{\"score\":\"1\",\"assess_name\":\"Crunches\",\"assess_no\":\"2\",\"value\":\"1\"},{\"score\":\"1\",\"assess_name\":\"PushUps\",\"assess_no\":\"3\",\"value\":\"1\"},{\"score\":\"1\",\"assess_name\":\"Plank\",\"assess_no\":\"4\",\"value\":\"1\"}]"
}
jschnasse
  • 8,526
  • 6
  • 32
  • 72
mano haran
  • 13
  • 3
  • Look into this question https://stackoverflow.com/questions/43844461 . There are two answers on how to deserialize JSON that is wrapped in Json. – jschnasse Oct 15 '18 at 09:02

1 Answers1

0
let apiResponseData = Data()//Suppose your Api returns Data
        do {
            //Always use [String: Any] for jsonObject and [Any] for jsonArray
            let mainJsonDitionary = try JSONSerialization.jsonObject(with: apiResponseData, options: .mutableLeaves) as! [String: Any]
            let firstJsonObject = mainJsonDitionary["usr_assess_hdr"] as! [String: Any]
            //as second json object is an json string so we first need to get string and then parse that json String again.
            let secondJsonString = mainJsonDitionary["usr_assess_dtl"] as! String
            let secondJsonStringData = secondJsonString.data(using: .utf8)
            let secondJsonArray = try JSONSerialization.jsonObject(with: apiResponseData, options: .mutableLeaves) as! [Any] // this json is jsonArray not a jsonObject so we use [Any]
            //Now use secondJsonArray and loop it to get your desired data
            for obj in secondJsonArray {
                let jsonObj = obj as! [String: Any]
            }
        }
        catch let error {
            print("Error while Parsing JSON \(error.localizedDescription)")
        }

Ignore Force Unwrapping, you should nil check your code at every necessary step.

Syed Qamar Abbas
  • 3,637
  • 1
  • 28
  • 52