Parsing JSON information in Objective C (multiple levels) - ios

I'm able to parse a part of my JSON file but if I want to go deeper in the structure, I'm lost. Here's my JSON :
{
"album":[
{
"album_titre":"Publicité",
"album_photo":"blabla.jpg",
"album_videos":[
{
"titre_video":"Chauffage Compris",
"duree_video":"01'25''",
"photo_video":"chauffage.jpg",
"lien_video":"www.bkjas.jhas.kajs"
},
{
"titre_video":"NIFFF 2012",
"duree_video":"01'43''",
"photo_video":"nifff.jpg",
"lien_video":"www.bkjas.jhas.kajs"
}
]
},
{
"album_titre":"Events",
"album_photo":"bloublou.jpg",
"album_videos":[
{
"titre_video":"Auvernier Jazz",
"duree_video":"01'15''",
"photo_video":"auvernier.jpg",
"lien_video":"www.bkjas.jhas.kajs"
},
{
"titre_video":"NIFFF 2011",
"duree_video":"01'03''",
"photo_video":"nifff2011.jpg",
"lien_video":"www.bkjas.jhas.kajs"
}
]
},
{
"album_titre":"Culture",
"album_photo":"bilibl.jpg"
},
{
"album_titre":"Postproduction",
"album_photo":"bizoubzou"
}
]
}
And here's my objective-c code :
- (void)fetchedData:(NSData *)responseData {
NSError* error;
NSDictionary *document = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
if (document==nil)
{
NSLog( #"oops\n%#", error);
}
NSArray *album = document[#"album"];
for( NSDictionary *albumDictionary in album )
{
[album_titre addObject:albumDictionary[#"album_titre"]];
[album_photo addObject:albumDictionary[#"album_photo"]];
for( NSDictionary *album_videosDictionary in albumDictionary[#"album_videos"])
{
[titre_video addObject:album_videosDictionary[#"titre_video"]];
[duree_video addObject:album_videosDictionary[#"duree_video"]];
[photo_video addObject:album_videosDictionary[#"photo_video"]];
[lien_video addObject:album_videosDictionary[#"lien_video"]];
}
}
[self.tableView reloadData];
}
What I can't achieve is to create an array with for example contains all "titre_video" corresponding to "album_titre":"publicité". So it should contain "Chauffage Compris" and "Nifff 2012".
I know it's a kind of easy question but I've search for a while and still not able to do it.
Thank's a lot.
Nicolas

The key is to understand JSON structure:
{ } - - this means the underlying object is a dictionary.
[ ] -- this means the underlyingobject is an array
- (void)fetchedData:(NSData *)responseData {
NSError* error;
NSDictionary *document = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
// all titre:video for album_titre:publicite
NSArray *albumArray = [document objectForKey:#"album"];
NSDictionary *dict = [albumArray objectAtindex:0];
NSArray *videos = [dict objectForKey:#"album_videos"];
// to fetch Videos inside album_videos
// here you will get al the videos inside key titre_video
NSMutableArray *titreVideoArray = [[NSMutableArray alloc]init];
for(int i=0; i< videos.count; i++){
NSDictionary *dict = [videos objectAtindex:i];
NSArray *titreVideos = [dict objectForKey:#"titre_video"];
[titreVideoArray addObject: titreVideos];
}
}
It seems you want to fetch all the videos relating to different "album_titre".
I would suggest you to use NSPredicate .
NSArray *videos = [self videosArrayForTitle:#"Publicité" albumArray:albumArray];
Here we pass title and the albumArray from above to fetch us the videos array.
- (NSArray *)videosArrayForTitle:(NSString *)title albumArray:(NSArray *)albumArray{
NSPredicate *resultPredicate=[NSPredicate predicateWithFormat:#"SUBQUERY(album_titre, $content, $content CONTAINS %#).#count > 0", title];
NSArray *searchResults=[albumArray filteredArrayUsingPredicate:resultPredicate];
NSArray *videos = [searchResults objectForKey:#"album_videos"];
return videos;
}

{ } denotes NSDictionary
[ ] denotes NSArray
Copy your json into a text edit file and go in deep. You can use NSLog() to print the data, when you go deep.
Hope it will help you.

Related

Extract JSON and save it in NSMutableArray

Following is the my JSON, and i want to extract the data and save it to a NSMutableArray. However, this doesn't get extracted accurately. I am stuck with this for awhile now. Can someone help me out ?
Note: I want the JSON to be extracted as it is. With each sub category.
{
"Animal":[
{
"Dog":[
{
"id":"644"
}
]
},
{
"Cat":[
{
"id":"4125"
},
{
"id":"1326"
}
]
},
{
"Mouse":[
{
"id":"224"
},
{
"id":"245"
}
]
},
{
"Fish":[
{
"id":"144"
},
{
"id":"142"
}
]
}
]
}
I need to add these components to a NSMutableArray. How can i do this ?
animalArray = [[NSMutableArray alloc] init];
for (int i =0; i < [[jsonDict objectForKey:#"Animal"] count]; i++) {
dictionary= [[NSMutableDictionary alloc] init];
for (int k =0; k < [[[jsonDict objectForKey:#"Animal"] objectAtIndex:i] count]; k++) {
dictionary setObject:[[[[jsonDict objectForKey:#"Animal"] objectAtIndex:i] objectAtIndex:k] objectForKey:#"id"] forKey:#"id"];
[animalArray addObject: dictionary];
}
}
Try this to get a NSDictionary object of exact structure that of the JSON
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData // this is your JSON
options:NSJSONReadingMutableContainers
error:&jsonError];
NSLog(#"%#",json); // check the structure here
I deep recommend use Mantle Library for parse JSON content:
Mantle Lib
And here a good introduction tutorial how use this lib:
How use mantle lib
You will see how easy is parsing and use data latter , and question please fell free for ask

Incorrectly parse json into NSDictionary

I am trying store text fields data into a NSDictionary from json. I have used SBJson for this.
{
"fields":[
{
"textFields":[
{
"text":"Congratulations",
"textSize":"12"
},
{
"text":"Best Wishes",
"textSize":"15"
},
{
"text":"Test text",
"textSize":"10"
}
]
},
{
"imageFields":[
{
"image":"test1.jpg",
"width":"200",
"height":"100"
},
{
"image":"test2.jpg",
"width":"200",
"height":"100"
}
]
}
]
}
My code:
-(void)readJson{
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *fieldsDict =[jsonDict valueForKey:#"fields"];
NSDictionary *textFieldsDict = [fieldsDict valueForKey:#"textFields"];
NSLog(#" Dictionary %# ",textFieldsDict );
}
But its output as follows.
Dictionary (
(
{
text = Congratulations;
textSize = 12;
},
{
text = "Best Wishes";
textSize = 15;
},
{
text = "Test text";
textSize = 10;
}
),
"<null>"
)
It seems like there are two items in dictionary and one is null. I wanted to put three textfield items into the array. How can i solve this.
Don't use SBJSON. Use NSJSONSerialization.
Don't use valueForKey:, use objectForKey:.
You are mixing up dictionaries and arrays. Don't do that. Use NSArray for arrays.
I am revising your code for better understanding
-(void)readJson
{
NSDictionary *jsonDict = [jsonString JSONValue];
NSDictionary *fieldsDict =[jsonDict valueForKey:#"fields"];
NSDictionary *textFieldsDict = [fieldsDict valueForKey:#"textFields"];
NSLog(#" Dictionary %# ",textFieldsDict );
}
More appropriate way is
-(void)readJson
{
NSDictionary *jsonDict = [jsonString JSONValue];
NSArray *fieldsArr =[jsonDict objectForKey:#"fields"];
for(int i=0;i<[fieldArr count];i++)
{
NSArray *textFieldArr = [fieldArr objectAtIndex: i];
for(int j=0;j<[textFieldArr count];j++)
{
NSDictionary *dicTextField = [textFieldArr objectAtIndex: j];
NSString *text = [dicTextField objectForKey: #"text"];
NSString *textSize = [dicTextField objectForKey: #"textSize"];
}
}
}
For quick help
treat { as dictionary and [ as array.
Hope, i am helpful to you.
As your json format, [jsonDict valueForKey:#"fields"] will return an array not dictionary so your code must be
NSDictionary *jsonDict = [jsonString JSONValue];
NSArray *fields = [jsonDict objectForKey:#"fields"];
NSDictionary *fieldsDict = fields[0];
NSArray *textFieldsDict = [fieldsDict objectForKey:#"textFields"];
I have corrected the json format and used NSJSONSerialization,
{"fields":
{"textFields":
[ {"text":"Congratulations", "textSize":"12"},
{"text":"Best Wishes", "textSize":"15"},
{"text":"Test text", "textSize":"10"}
],
"imageFields":
[ {"image":"test1.jpg","width":"200", "height":"100"},
{"image":"test2.jpg", "width":"200", "height":"100"}
]
}
}
-(void)readJson
NSError *e = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&e];
NSDictionary *fields = [jsonDict objectForKey:#"fields"];
NSArray *textArray=[fields objectForKey:#"textFields"] ;
NSLog(#"--- %#",textArray );
}

Parsing values from NSArray based on JSON format

I have a NSArray which is based on JSON format. I requested it from the web and saved it in the array. I am trying to use a dictionary to get the values of "categoryname" and "subscore" and store them in new arrays, but they remain empty. Do I have to convert the array back to NSData using JSON serialisation or is there a more direct way to achieve this?
NSArray detailedscore:
{
"articles": [
{
"abstract": "text",
"title": "title"
}
],
"subscore": 3,
"categoryname": "Reporting"
},
{
"articles": [
{
"abstract": "text2",
"title": "title"
}
],
"subscore": 1,
"categoryname": "Power"
}]
}
Code:
for(int i = 0; i < [self.detailedscore count]; i++)
{
NSMutableDictionary * dc = [self.detailedscore objectAtIndex:i];
NSString * score = [dc objectForKey:#"subscore"];
NSString * categoryname = [dc objectForKey:#"categoryname"];
[self.allscores addObject:subscore];
[self.allcategories addObject:categoryname];
for (NSString *yourVar in allcategories) {
NSLog (#"Your Array elements are = %#", yourVar);
}
{} ----> means dictionary, []---> array..... this is a rule I follow while assinging the return value from webservices as NSArray or NSDictionary....
Depending on your current JSON format, perhaps this might give you an idea
NSMutableArray *categoryArray = [NSMutableArray new];
for (NSDictionary *childDict in self.detailedscore)
{
[categoryArray addObject:[childDict objectForkey:#"categoryname"]];
}
If you have the array use below code
for(int i = 0; i < [self.detailedscore count]; i++)
{
NSMutableDictionary * dc = [self.detailedscore objectAtIndex:i];
NSString * score = [dc objectForKey:#"subscore"];
NSString * categoryname = [dc objectForKey:#"categoryname"];
[self.allscores score];
[self.allcategories addObject:categoryname];
for (NSString *yourVar in allcategories) {
NSLog (#"Your Array elements are = %#", yourVar);
}
The problem wasn't in the array or dictionary or the web request. I didn't allocated the NSMutableArrays so they were empty all the time. The code works fine for extracting values from the array in case anyone wants to use it.
Hope this helps.
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (!connectionError) {
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&connectionError];
NSLog(#"Dict %#",dict);
BOOL isValid = [NSJSONSerialization isValidJSONObject:dict];
if (isValid) {
[target getJSONFromresponseDictionary:dict forConnection:strTag error:connectionError];
}
else{
NSString *strResponse = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[target getStringFromresponseDictionary:strResponse forConnection:strTag error:error];
}

XML into JSON conversion in iOS

I need to convert XML response to JSON and sand to the json To javaScript code.
My XML response:
<cell>
<Result>True</Result>
<sguid>02291c402-2220-422b-b199-f92f22e56d2f</sguid>
</cell>
I am using XMLReader supporting file from this site:
XMLReader
I am using this code to convert XML to JSON :
+ (NSString*) XMLToJson:(CXMLDocument *)xmlDocument
{
NSError *error = nil;
NSArray *resultNodes = [xmlDocument nodesForXPath:#"//cell" error:&error];
if(error)
NSLog(#"%#",error.description);
CXMLNode *cellNode = [resultNodes objectAtIndex:0];
NSLog(#"%#",cellNode.XMLString);
NSError *parseError = nil;
NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:cellNode.XMLString error:&parseError];
NSLog(#"%#", xmlDictionary);
//{print this.
// cell = {
// Result = {
// text = True;
// };
// sguid = {
// text = "0391c402-1120-460b-b199-f92fffe56d2f";
// };
// };
//}
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:xmlDictionary
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
if(error)
NSLog(#"%#",error.description);
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"%#", jsonString);
return jsonString;
}
I got JSON response like this:
{
"cell" : {
"Result" : {
"text" : "True"
},
"sguid" : {
"text" : "0391c402-1120-460b-b199-f92fffe56d2f"
}
}
}
I need JSON response like this:
{
"cell": {
"Result": "True",
"sguid": "02291c402-2220-422b-b199-f92f22e56d2f"
}
}
Because then I send this json to javascript code I get that exception jquery mobile dont know parser this and throws an exception of syntax error.
I've seen programmers use this solution and is helping them but I still get the same result in this solution.
XML into JSON conversion in iOS
thanks
I just wrote a function for your problem, I tried it on with a couple of XMLs. Let me know if you find any issues
- (NSMutableDictionary *)extractXML:(NSMutableDictionary *)XMLDictionary
{
for (NSString *key in [XMLDictionary allKeys]) {
// get the current object for this key
id object = [XMLDictionary objectForKey:key];
if ([object isKindOfClass:[NSDictionary class]]) {
if ([[object allKeys] count] == 1 &&
[[[object allKeys] objectAtIndex:0] isEqualToString:#"text"] &&
![[object objectForKey:#"text"] isKindOfClass:[NSDictionary class]]) {
// this means the object has the key "text" and has no node
// or array (for multiple values) attached to it.
[XMLDictionary setObject:[object objectForKey:#"text"] forKey:key];
}
else {
// go deeper
[self extractXML:object];
}
}
else if ([object isKindOfClass:[NSArray class]]) {
// this is an array of dictionaries, iterate
for (id inArrayObject in (NSArray *)object) {
if ([inArrayObject isKindOfClass:[NSDictionary class]]) {
// if this is a dictionary, go deeper
[self extractXML:inArrayObject];
}
}
}
}
return XMLDictionary;
}
And use it like this
NSDictionary *clearXML = [[self extractXML:[yourParsedXMLDictionary mutableCopy]] copy];
Your problem in using XMLReader. For resolve this problem you can use XMLConverter instead of the XMLReader.

How can I get the JSON array data from nsstring or byte in xcode 4.2?

I'm trying to get values from nsdata class and doesn't work.
here is my JSON data.
{
"count": 3,
"item": [{
"id": "1",
"latitude": "37.556811",
"longitude": "126.922015",
"imgUrl": "http://175.211.62.15/sample_res/1.jpg",
"found": false
}, {
"id": "3",
"latitude": "37.556203",
"longitude": "126.922629",
"imgUrl": "http://175.211.62.15/sample_res/3.jpg",
"found": false
}, {
"id": "2",
"latitude": "37.556985",
"longitude": "126.92286",
"imgUrl": "http://175.211.62.15/sample_res/2.jpg",
"found": false
}]
}
and here is my code
-(NSDictionary *)getDataFromItemList
{
NSData *dataBody = [[NSData alloc] initWithBytes:buffer length:sizeof(buffer)];
NSDictionary *iTem = [[NSDictionary alloc]init];
iTem = [NSJSONSerialization JSONObjectWithData:dataBody options:NSJSONReadingMutableContainers error:nil];
NSLog(#"id = %#",[iTem objectForKey:#"id"]);
//for Test
output = [[NSString alloc] initWithBytes:buffer length:rangeHeader.length encoding:NSUTF8StringEncoding];
NSLog(#"%#",output);
return iTem;
}
how can I access every value in the JSON? Please help me.
look like this ..
NSString *jsonString = #"your json";
NSData *JSONdata = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError = nil;
if (JSONdata != nil) {
//this you need to know json root is NSDictionary or NSArray , you smaple is NSDictionary
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:JSONdata options:0 error:&jsonError];
if (jsonError == nil) {
//every need check value is null or not , json null like ( "count": null )
if (dic == (NSDictionary *)[NSNull null]) {
return nil;
}
//every property you must know , what type is
if ([dic objectForKey:#"count"] != [NSNull null]) {
[self setCount:[[dic objectForKey:#"count"] integerValue]];
}
if ([dic objectForKey:#"item"] != [NSNull null]) {
NSArray *itemArray = [dic objectForKey:#"item"]; // check null if need
for (NSDictionary *itemDic in itemArray){
NSString *_id = [dic objectForKey:#"id"]; // check null if need
NSNumber *found = (NSNumber *)[dic objectForKey:#"found"];
//.....
//.... just Dictionary get key value
}
}
}
}
I did it by using the framework : http://stig.github.com/json-framework/
It is very powerfull and can do incredible stuff !
Here how I use it to extract an item name from an HTTP request :
(where result is the JSO string)
NSString *result = request.responseString;
jsonArray = (NSArray*)[result JSONValue]; /* Convert the response into an array */
NSDictionary *jsonDict = [jsonArray objectAtIndex:0];
/* grabs information and display them in the labels*/
name = [jsonDict objectForKey:#"wine_name"];
Hope this will be helpfull
Looking at your JSON, you are not querying the right object in the object hierarchy. The top object, which you extract correctly, is an NSDictionary. To get at the items array, and the single items, you have to do this.
NSArray *items = [iTem objectForKey:#"item"];
NSArray *filteredArray = [items filteredArrayUsingPredicate:
[NSPredicate predicateWithFormat:#"id = %d", 2];
if (filteredArray.count) NSDictionary *item2 = [filteredArray objectAtIndex:0];
Try JSONKit for this. Is is extremely simple to use.
Note sure if this is still relevant, but in iOS 5, apple added reasonable support for JSON. Check out this blog for a small Tutorial
There is no need to import any JSON framework. (+1 if this answer is relevant)

Resources