-1

I am developing a swift iOS app and getting the following JSON response from web service. I am trying to parse and get nextResponse from it. I am unable to extract it. Could someone guide me to solve this?

listofstudents:
        ({
        studentsList =     (
                    {
                data =             (
                    "32872.23",
                    "38814.87",
                    "38915.85"
                );
                label = “name, parents and guardians”;
            }
        );
        dateList =     (
            "Apr 26, 2017",
            "Jun 10, 2017",
            "Jul 26, 2017"
        );
        firstResponse = “This school has 1432 students and 387 teachers.”;
        nextResponse = “This school has around 1400 students.”;
    })

Swift code:

    do {
                let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
                print("json: \(json)")

                if let parseJSON = json {

                    let finalResponse = parseJSON["listofstudents"] as? AnyObject
                    print("listofstudents::   \(finalResponse)")

                    let nextResponse = parseJSON["nextResponse"] as? AnyObject
                    print("nextResponse::   \(nextResponse)")
         }
            } catch {
                print(error)
            }
nathan
  • 9,329
  • 4
  • 37
  • 51
Stella
  • 1,728
  • 5
  • 41
  • 95

3 Answers3

3

Don't use NSDictionary in Swift, but use its native Swift counterpart, Dictionary. This is how you access dictionaries embedded inside other dictionaries:

do {
    guard let json = try JSONSerialization.jsonObject(with: data!) as? [String:Any] else {return}
    print("json: \(json)")

    guard let finalResponse = parseJSON["listofstudents"] as? [String:Any] else {return}
    print("listofstudents::   \(finalResponse)")

    guard let nextResponse = finalResponse["nextResponse"] as? [String:Any] else {return}
    print("nextResponse::   \(nextResponse)")
} catch {
    print(error)
}
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
1

nextResponse is part of the JSON structure (it's a nested node). So you should access it using:

typealias JSON = [String: Any]
if let finalResponse = parseJSON["listofstudents"] as? JSON {
    let nextResponse = finalResponse ["nextResponse"] as? JSON
    print("nextResponse::   \(nextResponse)")
}
nathan
  • 9,329
  • 4
  • 37
  • 51
1

Looks like your listofstudents is an array of dictionary so try to iterate it and extract it:-

if let finalResponse = parseJSON["listofstudents"] as? [String: Any] {
 //If your finalResponse has list then you can print all the data
  for response in finalResponse {
    let nextResponse = finalResponse ["nextResponse"] as? AnyObject
    print("nextResponse::\(nextResponse)")
  }
}
Hussain Shabbir
  • 14,801
  • 5
  • 40
  • 56