2

how can I get applicationStateJson in below code, I can parse the bellow JSON object from data but can not able to get applicationStateJson from it

{
applicationStateJson =     {
    "address_status" = 0;
    email = "xxxxxxxx;
    "email_status" = 0;
    "first_name" = xxx;
    "last_name" = "";
    "login_status" = 1;
    loginstype = "<null>";
    mobile = xxxxxx;
    "mobile_status" = 1;
    notifications =         (
    );
    "notifications_size" = 0;
    "otp_status" = 3;
    "profile_id" = "<null>";
    "profile_name" = "virtual_recruiter";
    "user_id" = 454;
    "user_status" = 1;
    "virtual_recruiter_id" =xxx;
};
"error_msg" = "<null>";
status = "<null>";
}

code as

do { 
 let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject 
print(json) 
let applicationStateJson = try json["applicationStateJson"] 
} catch { print(error.localizedDescription) } 
Anbu.Karthik
  • 82,064
  • 23
  • 174
  • 143
  • 2
    show your tried code always – Anbu.Karthik Nov 13 '17 at 09:56
  • do { let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject print(json) let applicationStateJson = try json["applicationStateJson"] } catch { print(error.localizedDescription) } – Bhavani Ayyamperumal Nov 13 '17 at 09:59
  • Possible duplicate of [Convert Dictionary to JSON in Swift](https://stackoverflow.com/questions/29625133/convert-dictionary-to-json-in-swift) – jegadeesh Nov 13 '17 at 10:00

2 Answers2

1

Try with below code

First you need to change in below line, its Dictionary<String, Any> not an AnyObject

let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.mutableContainers) as! Dictionary<String, Any> 

And then get applicationStateJson by below code

if let appJson = json["applicationStateJson"] as? Dictionary<String, Any> {
    print(appJson)
    print("Email : \(appJson["email"] as? String ?? "Email not found")") // For get email
} 
iPatel
  • 46,010
  • 16
  • 115
  • 137
0

The root object of the JSON is a clearly a dictionary, not AnyObject (an object but I-have-no-idea-what-it-is).

The value for key applicationStateJson is a dictionary, too.

do { 
   if let json = try JSONSerialization.jsonObject(with: data) as? [String:Any],
      let applicationStateJson = json["applicationStateJson"] as? [String:Any] {
         print(applicationStateJson)
   }
} catch { 
   print(error)
}

As always, .mutableContainers is completely meaningless in Swift

vadian
  • 274,689
  • 30
  • 353
  • 361