iOS to parse JSON? - objective-c

I am getting the following response from server
[{"id":"16","name":"Bob","age":"37"},{"id":"17","name":"rob","age":"28"}];
I am using AFNetworking framework for it,
I am getting the above response in NSData and then using the the below code, I am able to collect the data in NSDictionary
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:&error];
But how to parse the "name" and "age" value from that NSDictionary?

You expected NSDictionary but your response gives you array of dictionaries, try this:
NSArray *array = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:&error];
for (NSDictionary *dict in array)
{
NSLog(#"Name: %#, age: %#", dict[#"name"], dict[#"age"]);
}
//Extended
From the comment below it looks like you have a string from the response, not NSArray as you show in the code above.
You can parse string to get the data you want or you can convert it back to the json and NSArray:
NSString * jsonString = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:&error];
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//As I post above
Now you should have an NSArray and my code should do the job.

Related

Reading NSDictionary of JSON data

I have JSON data:
{"data":[
{"userID":"1", "username":"name1"},
{"userID":"2", "username":"name2"},
{"userID":"3", "username":"name3"}
]}
returned into an NSDictionary.
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:jsonReturnData options:kNilOptions error:&err];
The jsonObject looks like this:
How do I then read the values in the NSDictionary? I have:
NSDictionary *dictItem1 = (NSDictionary *)jsonObject;
which reads the data item but how do get the values?
Finally got it reading the data into an NSArray:
NSArray *JsonData = [NSJSONSerialization JSONObjectWithData:jsonReturnData options:NSJSONReadingAllowFragments error:&err];
NSArray *array = [JsonData objectAtIndex:0];
NSDictionary *dictItem = (NSDictionary *)array;
NSArray *arrayItems = [dictItem objectForKey:#"data"];
The arrayItems then held each of the records.
As pointed out it be further simplified with:
NSArray *JsonData = [NSJSONSerialization JSONObjectWithData:jsonReturnData options:NSJSONReadingAllowFragments error:&err];
NSDictionary *dictItem = (NSDictionary *)[JsonData objectAtIndex:0];;
NSArray *arrayItems = [dictItem objectForKey:#"data"];

Am stuck in parsing Push Notifications

I want to fetch value of description from the below response. In body few more key-value pairs are there. I have tried, unfortunately am failing to crack. My code is in Objective C.
And My code for Parsing as below
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:notification.request.content.userInfo options:0 error:NULL];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"After Validation JSON VALUE IS : %#", jsonString);
NSData *BodyData = [NSJSONSerialization dataWithJSONObject:[[[notification.request.content.userInfo objectForKey:#"aps"] objectForKey:#"alert"] objectForKey:#"body"] options:0 error:NULL];
NSString *BodyString = [[NSString alloc] initWithData:BodyData encoding:NSUTF8StringEncoding];
NSLog(#"After Validation JSON VALUE IS : %#", BodyString);
Here is my complete response. I want to fetch all the values from body section.
{
"aps":{
"alert":{
"title":"Your bill is ready from shop My Store",
"body":"{\"shop_id\":\"16\",\"shop_name\":\"My Store\",\"description\":\"Thank you for Shopping\",\"notification_type\":\"bill\",\"shop_category\":\"entertainment\",\"bill_date\":\"2018-01-13\",\"bill_url\":\"dXBsb2FkLzRvcmVfMDExMzIwMTgtMTY0NjI5LnBkZg==\",\"approve\":1}"
},
"sound":"1"
},
"gcm.message_id":"0:1515842219916508%a1c76c71a1c76c71",
"gcm.notification.vibrate":"1"
}
convert your body string to json
NSString*bodyKeyValue = #"{\"shop_id\":\"16\",\"shop_name\":\"My Store\",\"description\":\"Thank you for Shopping\",\"notification_type\":\"bill\",\"shop_category\":\"entertainment\",\"bill_date\":\"2018-01-13\",\"bill_url\":\"dXBsb2FkLzRvcmVfMDExMzIwMTgtMTY0NjI5LnBkZg==\",\"approve\":1}"; //[[[notification.request.content.userInfo objectForKey:#"aps"] objectForKey:#"alert"] objectForKey:#"body"];
NSData *data = [bodyKeyValue dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* jsonOutput = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#",jsonOutput);
NSLog(#"approve Key value:%#",[jsonOutput objectForKey:#"approve"]);

Storing JSON Data as a String Objective C

So i have gotten my Json data in which i have got:
{
"name": "brad"
}
I am trying to store that individual name as a string.
#try
{
NSError *error;
NSString *url_string = [NSString stringWithFormat: #"http://Share/scripts/newjson.json"];
///Dummy URL
NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString:url_string]];
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"json: %#", json);
}
#catch (NSException *e)
{
NSLog(#"Internet not enabled");
//something went wrong
//populate the NSError object so it can be accessed
}
But when i print out the json file i just get what is shown above, do i need to use a delimiter or something to get this string ?
Thanks
Actually the JSON is a dictionary not an array and with nilOptions not mutable.
To get brad write
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSString *name = json[#"name"];
NSLog(#"name: %#", name);

App crashing because NSArray objectforkey: Objective C

I am trying to parse some Json with Objective C.
My problem is that I am getting the correct json back but when I try parse some of the json my app crashes.
// i will use a code from connect to DB tutorial
NSString *strURL = [NSString stringWithFormat:#"http://www.ddproam.co.za/Central/Asset/AssetsWithSerial?Serial=S00000001"];
// to execute php code
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
// to receive the returend value
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSLog(#"Login response:%#",strResult);
NSError *error;
//parse out the json data
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:dataURL //1
options:kNilOptions
error:&error];
NSArray* defineJsonData = [json objectForKey:#"AssetDesc"]; //2
NSLog(#"value: %#", defineJsonData); //3
Here is my json:
[{"AssetID":1,"AssetName":"Asset 1","AssetDesc":"This is a manually inserted Asset","AssetTypeID":1,"AssetTypeDesc":"This is a manually inserted Asset Type"}]
I am trying to get the AssestName out of the string. I must be doing something wrong.
The whole thing is an array containing a dictionary, not a dictionary containing an array...
This is a very dirty way to get the value you want - you want to write something more safe than this. Try checking the type of class returned before you try to use it...
NSArray* json = [NSJSONSerialization JSONObjectWithData:dataURL //1
options:kNilOptions
error:&error];
NSDictionary* defineJsonData = [json lastObject]; //2
NSLog(#"value: %#", [defineJsonData objectForKey:#"AssetDesc"]); //3

Extract inner json data xcode with NSJSONSerialization

My json response from a URL is:
[
{"status":0,
"id":"26",
"content":"See info field for info",
"time":1347565292761,
"info": {"id":"26",
"name":"Ruti",
"twitterPageFollowers":null,
"facebookPageLikes":null,
"activeEmailClients":1}
}
]
I need to extract from it the following strings:
twitterPageFollowers
facebookPageLikes
activeEmailClients
How can I do it?
I tried parsing like this
NSData *urlData=[NSURLConnection sendSynchronousRequest:serviceRequest returningResponse:nil error:nil ];
NSString *returnString=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSData *jsonData = [returnString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
NSDictionary *response = [json objectAtIndex:0];
NSString *info = [response objectForKey:#"info"];
NSData *businessInfoString = [info dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *businessInfo =
[NSJSONSerialization JSONObjectWithData: businessInfoString
options: NSJSONReadingMutableContainers
error: nil];
And the return data is ok, but I get [__NSCFDictionary dataUsingEncoding:unrecognized selector sent to instance for the last NSDictionary creation from info field.
What is wrong or what is the shorter way to retrieve the above fields?
When you retrieve the "info" field using [response objectForKey:#"info"];, you already get an NSDictionary! (and NOT an NSString).
That's why when you try to call dataUsingEncoding: on this object (that you believed was an NSString but is as NSDictionary) you get the exception.
There is no need to retrieve the value of "info" key then converting it to NSData and converting it back a JSONObject, because it is already a JSONObject, namely an NSDictionary in your case. Why bother trying to convert it back and forth, whereas [response objectForKey:#"info"]; already returns that businessInfo dictionary that you expect at the end of your code?