Parse a nested Json to NSDictionary in iOS - objective-c

I Have a nested Json :
[
{
"result":"1",
"roleId":4
},
{
"projectInfo":[
{
"result":true
},
{
"Project":[
{
"ProjectId":5378,
"ProjectName":"ASAG",
"CountryId":146,
"ProjectGroupId":743,
"Description":"Axel Spinger AG"
},
{
"ProjectId":5402,
"ProjectName":"BIZ",
"CountryId":146,
"ProjectGroupId":759,
"Description":"Bizerba Win 7 BAU"
},
{
"ProjectId":5404,
"ProjectName":"BOM",
"CountryId":146,
"ProjectGroupId":743,
"Description":"Bombardier Transportation ThinApp Migration"
},
{
"ProjectId":5394,
"ProjectName":"REDBULL",
"CountryId":149,
"ProjectGroupId":762,
"Description":"Red Bull Mac Packaging"
},
{
"ProjectId":5397,
"ProjectName":"VHV",
"CountryId":146,
"ProjectGroupId":743,
"Description":"VHV Win7 Migration"
}
]
}
]
}
]
What I need is to separate it into small pieces to get value of some specific key like this answer: How to parse JSON into Objective C - SBJSON
My code is :
SBJsonParser* jParser = [[SBJsonParser alloc] init];
NSDictionary* root = [jParser objectWithString:string];
NSDictionary* projectInfo = [root objectForKey:#"projectInfo"];
NSArray* projectList = [projectInfo objectForKey:#"Project"];
for (NSDictionary* project in projectList)
{
NSString *content = [project objectForKey:#"ProjectId"];
NSLog(#"%#", content);
}
But I got the error when trying to get projectInfo from root node. Is there anything wrong with my code ? Please provide me an example to split up my JSON. Any help would be great.

You JSON contains like nested array. Just spit each content into a dictionary to get the result.
Working Code:
SBJsonParser* jParser = [[SBJsonParser alloc] init];
NSArray* root = [jParser objectWithString:string];
NSDictionary* projectDictionary = [root objectAtIndex:1];
NSArray* projectInfo = [projectDictionary objectForKey:#"projectInfo"];
NSDictionary* projectData = [projectInfo objectAtIndex:1];
NSDictionary *projectList = [projectData objectForKey:#"Project"];
NSLog(#"\n\n Result = %#",projectList
);
for (NSDictionary* project in projectList)
{
NSString *content = [project objectForKey:#"ProjectId"];
NSLog(#"\n Project Id =%#", content);
}

According to your JSON structure, your top level structure is an array, not a dictionary.
Try this:
SBJsonParser* jParser = [[SBJsonParser alloc] init];
NSArray* root = [jParser objectWithString:string];
NSDictionary* projectDictionary = [root objectAtIndex:1];
NSArray* projectInfo = [projectDictionary objectForKey:#"projectInfo"];

Related

how to parse this JSON in OBJ c

I receive this JSON string from a web process
{
"result":"ok",
"description":"",
"err_data":"",
"data":[
{
"id":"14D19A9B-3D65-4FE2-9ACE-4C2D708DAAD8"
},
{
"id":"8BFD10B8-F5FD-4CEE-A307-FE4382A0A7FD"
}
]
}
and when I use the following to get the data:
NSError *jsonError = nil;
NSData *objectData = [ret dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json= [NSJSONSerialization JSONObjectWithData: objectData options:kNilOptions error: &jsonError];
NSLog(#"data: %#",[json objectForKey:#"data"]);
it gets logged as:
(
{
id = "14D19A9B-3D65-4FE2-9ACE-4C2D708DAAD8";
},
{
id = "8BFD10B8-F5FD-4CEE-A307-FE4382A0A7FD";
}
)
How can I parse the data as an NSDictionary with value and keys?
The web returns an object that has a property which is an array of objects, so...
NSDictionary *json= // your code
NSArray *array = json[#"data"];
for (NSDictionary *element in array) {
NSLog(#"%#", element);
// or, digging a little deeper
NSString *idString = element[#"id"];
NSLog(#"id=%#", idString);
}

How to parse the JSON string from invoked adapter in Worklight

We have a JSON file in the server. We were able to retrieve the JSON file, but apparently we could not get the items in the nested JSON.
Here is the snippet of our code:
- (void)onSuccess:(WLResponse *)response{
NSLog(#"Connection Success: %#",response);
NSString *resultText;
if ([response responseText] != nil) {
resultText = [response responseText];
NSDictionary *allData = [response getResponseJson];
NSDictionary *resultData = allData[#"result"];
...
}
}
Below is our JSON file structure:
{"contacts":[
{
"name":"name 1",
"address":"address 1"
},
{
"name":"name 2",
"address":"address 2"
},
{
"name":"name 3",
"address":"address 3"
}
]}
You can use valueForKeyPath: after you have an NSDictionary on the client.
For example, pseudocode:
NSArray* contacts = [allData valueForKeyPath:#"result.contacts"];
NSString* firstContactName = contacts[0][#"name"];
I assume your NSDictionary referenced by allData has the contacts NSArray in the results.contacts key path. If that's not the case, modify according to the structure of your NSDictionary.

JSONKit Parsing Nested JSON with Objective-C

I am trying to parse my nested JSON with JSONKit and the 2nd level JSON isn't being parsed correctly.
Here's sample JSON...
{
"app": {
"content": "[{\\\"Id\\\":\\\"1\\\",\\\"Name\\\":\\\"John\\\"},{\\\"Id\\\":\\\"2\\\",\\\"Name\\\":\\\"John\\\"}]"
}
}
and Here's my code...
NSString *jsonString = "...long nested json string...";
NSDictionary *jsonParsed = [jsonString objectFromJSONString];
NSString *content = [[jsonParsed objectForKey:#"app"] objectForKey:#"content"];
NSDictionary *jsonContent = [content objectFromJSONString];
NSLog(#"%#", jsonContent);
Where am I going wrong?
This is quite easy to answer: You are escaping \ as well as ". So your result in the NSString* content will be \". This is something your JSON parser won't digest. So use instead of \\\" this \".
If you replace the content string with following:
"[{\"Id\":\"1\",\"Name\":\"John\"},{\"Id\":\"2\",\"Name\":\"John\"}]"
It will be parsed correctly.
JSON.parse("[{\"Id\":\"1\",\"Name\":\"John\"},{\"Id\":\"2\",\"Name\":\"John\"}]")
>>> [Object { Id="1", Name="John"}, Object { Id="2", Name="John"}]
Maybe you have escaped the content string twice at somewhere in your code.
I just used firebug to see if the JSON was correct. JSONKit is the same:
clowwindy:~ clowwindy$ cat /tmp/input.txt
{
"app": {
"content": "[{\"Id\":\"1\",\"Name\":\"John\"},{\"Id\":\"2\",\"Name\":\"John\"}]"
}
}
NSError *error;
NSString *input = [NSString stringWithContentsOfFile:#"/tmp/input.txt" encoding:NSUTF8StringEncoding error:&error];
NSString *jsonString = input;
NSDictionary *jsonParsed = [jsonString objectFromJSONString];
NSString *content = [[jsonParsed objectForKey:#"app"] objectForKey:#"content"];
NSDictionary *jsonContent = [content objectFromJSONString];
NSLog(#"%#", jsonContent);
NSLog(#"%#", content);
2012-01-02 00:26:39.818 testjson[12700:707] (
{
Id = 1;
Name = John;
},
{
Id = 2;
Name = John;
}
)
2012-01-02 00:26:39.822 testjson[12700:707] [{"Id":"1","Name":"John"},{"Id":"2","Name":"John"}]

JSON and 2D array

The following is encoded JSON data from a PHP webpage.
{
{
"news_date" = "2011-11-09";
"news_id" = 5;
"news_imageName" = "newsImage_111110_7633.jpg";
"news_thread" = "test1";
"news_title" = "test1 Title";
},
{
"news_date" = "2011-11-10";
"news_id" = 12;
"news_imageName" = "newsImage_111110_2060.jpg";
"news_thread" = "thread2";
"news_title" = "title2";
},
// and so on...
}
I'd like to grab one buch of info (date/id/image/thread/title), and store it as an instance of a class. However, I have no clue on how to access each object in 2D arrays.
The following is the code I've written to test if I can access them, but it doesn't work.
What would be the problem?
NSURL *jsonURL = [NSURL URLWithString:#"http://www.sangminkim.com/UBCKISS/category/news/jsonNews.php"];
NSString *jsonData = [[NSString alloc] initWithContentsOfURL:jsonURL];
SBJsonParser *parser = [[SBJsonParser alloc] init];
contentArray = [parser objectWithString:jsonData];
NSLog(#"array: %#", [[contentArray objectAtIndex:0] objectAtIndex:0]); // CRASH!!
In JSON terminology, that’s not a two-dimensional array: it’s an array whose elements are objects. In Cocoa terminology, it’s an array whose elements are dictionaries.
You can read them like this:
NSArray *newsArray = [parser objectWithString:jsonData];
for (NSDictionary *newsItem in newsArray) {
NSString *newsDate = [newsItem objectForKey:#"news_date"];
NSUInteger newsId = [[newsItem objectForKey:#"news_id"] integerValue];
NSString *newsImageName = [newsItem objectForKey:#"news_imageName"];
NSString *newsThread = [newsItem objectForKey:#"news_thread"];
NSString *newsTitle = [newsItem objectForKey:#"news_title"];
// Do something with the data above
}
You gave me a chance to checkout iOS 5 Native JSON parser, so no external libraries needed, try this :
-(void)testJson
{
NSURL *jsonURL = [NSURL URLWithString:#"http://www.sangminkim.com/UBCKISS/category/news/jsonNews.php"];
NSData *jsonData = [NSData dataWithContentsOfURL:jsonURL];
NSError* error;
NSArray* json = [NSJSONSerialization
JSONObjectWithData:jsonData //1
options:kNilOptions
error:&error];
NSLog(#"First Dictionary: %#", [json objectAtIndex:0]);
//Log output:
// First Dictionary: {
// "news_date" = "2011-11-09";
// "news_id" = 5;
// "news_imageName" = "newsImage_111110_7633.jpg";
// "news_thread" = " \Uc774\Uc81c \Uc571 \Uac1c\Ubc1c \Uc2dc\Uc791\Ud574\Ub3c4 \Ub420\Uac70 \Uac19\Uc740\Ub370? ";
// "news_title" = "\Ub418\Ub294\Uac70 \Uac19\Uc9c0?";
// }
//Each item parsed is an NSDictionary
NSDictionary* item1 = [json objectAtIndex:0];
NSLog(#"Item1.news_date= %#", [item1 objectForKey:#"news_date"]);
//Log output: Item1.news_date= 2011-11-09
}

How to convert data to JSON format, using SBJSON iPhone SDK?

I want to convert the given data to JSON format ... please help me to overcome this problem. Thanks in advance.
{
data = (
{
id = 1307983297;
name = "Aafaaq Mehdi";
},
{
id = 1350886273;
name = "Shah Asad";
},
{
id = 1636300537;
name = "Imran Baig";
},
{
id = 1640049813;
name = "Vinod Gowda";
}
);
}
UPDATE:
NSDictionary *dict = [[NSDictionary alloc] initWithDictionary:appDelegate.friendList];
results= (NSArray *)[dict valueForKey:#"data"];
NSMutableArray *arr = [[NSMutableArray alloc] init];
// loop over all the results objects and print their names
int ndx;
for (ndx = 0; ndx < results.count; ndx++)
{
[arr addObject:(NSDictionary *)[results objectAtIndex:ndx]];
}
FriendListModel *obj;
for (int x=0; x<[arr count]; x++)
{
obj = [[[FriendListModel alloc] initWithjsonResultDictionary:[arr objectAtIndex:x]] autorelease];
[arr replaceObjectAtIndex:x withObject:obj];
NSMutableArray *facebookJSON = [[[NSMutableArray alloc] init] autorelease];
for (obj in arr) {
NSDictionary *syedDict = [NSDictionary dictionaryWithObjectsAndKeys:obj.friendId,#"id", obj.friendName, #"name", nil];
NSString *facebookJSONFormat = [syedDict JSONRepresentation];
[facebookJSON addObject:facebookJSONFormat];
}
NSString *myArrayString = [facebookJSON description];
NSString *braceInArr = [NSString stringWithFormat:#"[%#]", myArrayString];
[self setFormDataRequest:[ASIFormDataRequest requestWithURL:url]];
[formDataRequest setDelegate:self];
[formDataRequest setPostValue:braceInArr forKey:#"friend_list"];
[formDataRequest setDidFailSelector:#selector(uploadFailed:)];
[formDataRequest setDidFinishSelector:#selector(uploadFinished:)];
[formDataRequest startAsynchronous];
I got the output in this format:-
[(
"{\"id\":\"1307983297\",\"name\":\"No Man\"}",
"{\"id\":\"1350886273\",\"name\":\"Shah Asad\"}",
"{\"id\":\"1636300537\",\"name\":\"Imran Baig\"}",
"{\"id\":\"1640049813\",\"name\":\"Vinod Gowda\"}"
)]
{
"data":[
{
"id": 1307983297,
"name": "Aafaaq Mehdi"
},
{
"id": 1350886273,
"name": "Shah Asad"
},
{
"id": 1636300537,
"name": "Imran Baig"
},
{
"id": 1640049813,
"name": "Vinod Gowda"
}
]
}
That's your dad in JSON format... as for converting it, do you have a parser for the original format?