Extract inner json data xcode with NSJSONSerialization - objective-c

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?

Related

How to convert an NSString of JSON objects to an NSArray?

I'm having trouble converting my NSString of JSON objects to an NSArray.
The NSArray object seems to be null.
Here is my NSString JSON code:
NSString* retrievedStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
This gives me a printout of:
{"image_link":"schedule_tien_nguyen.jpg","start_time":"18:00","end_time":"19:00","viet_performer":"","english_performer":"Tien
Nguyen","viet_event":"","english_event":"Singing","day":0,"stage":0}
....
I tried to convert the NSString to an NSArray using:
NSArray *jsonObject = [NSJSONSerialization JSONObjectWithData:
[retrievedStr dataUsingEncoding:NSUTF8StringEncoding]
options:0 error:&error];
However the printout of the jsonObject is (null)
I have tried the solutions from here:
Converting an NSString of JSON Data to NSArray and How to convert a JSON String into an NSArray? but it's still printing out null.
The error printout states:
"Garbage at end."
I'm not sure what that means?
Try the following to read your JSON response. As others have mentioned, it's a JSON dictionary, not an NSArray. The dictionary may contain arrays, but the object response itself is a dictionary.
NSString* retrievedStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSString *imageLink = (NSString *)[retrievedStr objectForKey:#"image_link"]
NSLog(#"%#", imageLink);
use NSArray *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];

parsing NSString data-getting null value

I am parsing and NSString value but getting null in console. Please help me with the issue.
NSString *responseData = [[NSString alloc] initWithData:_responseData encoding:NSASCIIStringEncoding];
NSLog(#"Data: %#", responseData);
NSData *data = [responseData dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *res = [json objectForKey:#"demo"];
NSLog(#"res is %#",res);
I was having a similar problem in one of my projects. I was trying to create NSString from NSData(response from webservice) and i was getting a nil. I found out that using NSASCIIStringEncoding when creating the String solved my problem. It turns out that even though UTF8 has all ASCII chars, char * may not line up correctly for certain characters and by default the init methods do nonlossy encoding which means that nil gets returned when an unexpected char is encountered.
For your case this could be your code.
NSString *responseData = [[NSString alloc] initWithData:_responseData encoding:NSASCIIStringEncoding];
NSLog(#"Data: %#", responseData);
NSData *data = [responseData dataUsingEncoding:NSASCIIStringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSDictionary *res = [json objectForKey:#"demo"];
NSLog(#"res is %#",res);
NOTE: I am not sure why you are doing all the _responseData->data conversion. If you are doing that just to deserialize your _responseData to json object, you could use it directly in NSJSONSerialization. As below.
id json = [NSJSONSerialization JSONObjectWithData:_responseData options:0 error:nil];
For more information check out this link.
Maybe error appear because you using different encoding? Try using NSUTF8StringEncoding in NSString and in NSData.
From NSString class reference:
-initWithData:encoding:
Return Value
An NSString object initialized by converting the bytes in data into Unicode characters using encoding. The returned
object may be different from the original receiver. Returns nil if the
initialization fails for some reason (for example if data does not
represent valid data for encoding).
Where are you getting _responseData from? Is it definitely an NSDataobject?
Are you sure that you are using the correct encoding?
Could you print out _responseData and update your question so we can take a look?

iOS to parse JSON?

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.

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

Parsing special characters in JSON

I'm now parsing with NSJSONSerialization
NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"url"]];
NSError *jsonError = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&jsonError];
NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
[self setTableData:jsonDictionary];
But it won't parse my JSON because of special characters in the JSON like the letter 'ü' when i remove the 'ü' from the JSON it's working correclty. I tried the code above and:
options:utf8...
Does anyone know how i can fix this?
Try using NSString with which you can explicitly specify encoding. Ex:
NSString *string = [NSString stringWithContentsOfURL:webURL encoding:NSUTF8StringEncoding error:&error];
You can then convert the NSString object to NSData and then do the JSON serialisation..
Try to change NSJSONReadingMutableContainers with NSJSONReadingMutableLeaves. This solved me similar problem.