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.
Related
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);
}
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"];
Trying to parse this JSON object in objective-C and creating an NSArray with these objects.
The first value is a counter and is specific for the object. All other values are unique.
{ "myData": [
["1","1","110","dollar","8.0","2.8","0.1","11.6"],
["2","1","110","euro","4.0","3.2","1.5","4.4"],
["3","1","120","rupier","6.0","2.9","1.3","10.8"],
["4","1","120","dinero","4.0","3.3","1.5","4.4"],
["5","2","130","drahmer","8.0","2.9","1.3","11.2"],
] }
Tried this code:
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:myData
options:kNilOptions
error:&error];
NSArray *currencyInformation = [json objectForKey:#"myData"];
But the objects are not there. Though the count of the array is 5.
Each object in the array is an array itself, so:
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:myData
options:kNilOptions
error:&error];
NSArray *currencyInformation = [json objectForKey:#"myData"];
for (NSArray *info in currencyInformation) {
// Then access each "column" with [info objectAtIndex:0,1,2,3,...]
}
In this data structure you would need to access things by index e.g
for (NSArray *currency in currencyInformation) {
NSLog(#"Currency: %#", [currency objectAtIndex:3]);
}
If you want to access things by key then you would need to change your JSON to use an array of objects instead of an array of arrays. Something like this:
{
"myData": [
{
"primaryKey" : 1,
"currency" : "dollar",
<other keys + values>...
},
]
}
In which case you could now do something like:
for (NSDictionary *currency in currencyInformation) {
NSLog(#"Currency: %#", [currency valueForKey:#"currency"]);
}
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"}]
I am new to iPhone. Can anyone tell me the steps to follow to parse this data and get the activity details, first name, and last name?
{
"#error": false,
"#data": {
"": {
"activity_id": "35336",
"user_id": "1",
"user_first_name": "Chandra Bhusan",
"user_last_name": "Pandey",
"time": "1300870420",
"activity_details": "Good\n",
"activity_type": "status_update",
"photo_url": "http://184.73.155.44/hcl-meme/QA_TEST/sites/default/files/pictures/picture-1627435117.jpg"
},
"boolean": "1",
"1": {
"1": {
"photo_1_id": "9755"
},
"activity_id": "35294",
"album_name": "Kalai_new_Gallery",
"user_id": "31",
"album_id": "9754",
"user_first_name": "Kalaiyarasan",
"user_last_name": "Balu",
"0": {
"photo_0_id": "9756"
},
"time": "1300365758",
"activity_type": "photo_upload",
"photo_url": "http://184.73.155.44/hcl-meme/QA_TEST/"
},
"3": {
"activity_id": "35289",
"user_id": "33",
"user_first_name": "Girija",
"user_last_name": "S",
"time": "1300279636",
"activity_details": "girija Again\n",
"activity_type": "status_update",
"photo_url": "http://184.73.155.44/hcl-meme/QA_TEST/sites/default/files/pictures/picture-33-6361851323080768.jpg"
},
"2": {
"owner_first_name": "Girija",
"activity_id": "35290",
"activity_details": "a:2:{s:4:\"html\";s:51:\"!user_fullname and !friend_fullname are now friends\";s:4:\"type\";s:10:\"friend_add\";}",
"activity_type": "friend accept",
"owner_last_name": "S",
"time": "1300280400",
"photo_url": "http://184.73.155.44/hcl-meme/QA_TEST/sites/default/files/pictures/picture-33-6361851323080768.jpg",
"owner_id": "33"
},
"4": {
"activity_id": "35288",
"user_id": "33",
"user_first_name": "Girija",
"user_last_name": "S",
"time": "1300279530",
"activity_details": "girija from mobile\n",
"activity_type": "status_update",
"photo_url": "http://184.73.155.44/hcl-meme/QA_TEST/sites/default/files/pictures/picture-33-6361851323080768.jpg"
}
}
}
With the perspective of the OS X v10.7 and iOS 5 launches, probably the first thing to recommend now is NSJSONSerialization, Apple's supplied JSON parser. Use third-party options only as a fallback if you find that class unavailable at runtime.
So, for example:
NSData *returnedData = ...JSON data, probably from a web request...
// probably check here that returnedData isn't nil; attempting
// NSJSONSerialization with nil data raises an exception, and who
// knows how your third-party library intends to react?
if(NSClassFromString(#"NSJSONSerialization"))
{
NSError *error = nil;
id object = [NSJSONSerialization
JSONObjectWithData:returnedData
options:0
error:&error];
if(error) { /* JSON was malformed, act appropriately here */ }
// the originating poster wants to deal with dictionaries;
// assuming you do too then something like this is the first
// validation step:
if([object isKindOfClass:[NSDictionary class]])
{
NSDictionary *results = object;
/* proceed with results as you like; the assignment to
an explicit NSDictionary * is artificial step to get
compile-time checking from here on down (and better autocompletion
when editing). You could have just made object an NSDictionary *
in the first place but stylistically you might prefer to keep
the question of type open until it's confirmed */
}
else
{
/* there's no guarantee that the outermost object in a JSON
packet will be a dictionary; if we get here then it wasn't,
so 'object' shouldn't be treated as an NSDictionary; probably
you need to report a suitable error condition */
}
}
else
{
// the user is using iOS 4; we'll need to use a third-party solution.
// If you don't intend to support iOS 4 then get rid of this entire
// conditional and just jump straight to
// NSError *error = nil;
// [NSJSONSerialization JSONObjectWithData:...
}
Don't reinvent the wheel. Use json-framework or something similar.
If you do decide to use json-framework, here's how you would parse a JSON string into an NSDictionary:
SBJsonParser* parser = [[[SBJsonParser alloc] init] autorelease];
// assuming jsonString is your JSON string...
NSDictionary* myDict = [parser objectWithString:jsonString];
// now you can grab data out of the dictionary using objectForKey or another dictionary method
NSString* path = [[NSBundle mainBundle] pathForResource:#"index" ofType:#"json"];
//将文件内容读取到字符串中,注意编码NSUTF8StringEncoding 防止乱码,
NSString* jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
//将字符串写到缓冲区。
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
id allKeys = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONWritingPrettyPrinted error:&jsonError];
for (int i=0; i<[allKeys count]; i++) {
NSDictionary *arrayResult = [allKeys objectAtIndex:i];
NSLog(#"name=%#",[arrayResult objectForKey:#"storyboardName"]);
}
file:
[
{
"ID":1,
"idSort" : 0,
"deleted":0,
"storyboardName" : "MLMember",
"dispalyTitle" : "76.360779",
"rightLevel" : "10.010490",
"showTabBar" : 1,
"openWeb" : 0,
"webUrl":""
},
{
"ID":1,
"idSort" : 0,
"deleted":0,
"storyboardName" : "0.00",
"dispalyTitle" : "76.360779",
"rightLevel" : "10.010490",
"showTabBar" : 1,
"openWeb" : 0,
"webUrl":""
}
]
JSON parsing using NSJSONSerialization
NSString* path = [[NSBundle mainBundle] pathForResource:#"data" ofType:#"json"];
//Here you can take JSON string from your URL ,I am using json file
NSString* jsonString = [[NSString alloc] initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *jsonError;
NSArray *jsonDataArray = [NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding] options:kNilOptions error:&jsonError];
NSLog(#"jsonDataArray: %#",jsonDataArray);
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&jsonError];
if(jsonObject !=nil){
// NSString *errorCode=[NSMutableString stringWithFormat:#"%#",[jsonObject objectForKey:#"response"]];
if(![[jsonObject objectForKey:#"#data"] isEqual:#""]){
NSMutableArray *array=[jsonObject objectForKey:#"#data"];
// NSLog(#"array: %#",array);
NSLog(#"array: %d",array.count);
int k = 0;
for(int z = 0; z<array.count;z++){
NSString *strfd = [NSString stringWithFormat:#"%d",k];
NSDictionary *dicr = jsonObject[#"#data"][strfd];
k=k+1;
// NSLog(#"dicr: %#",dicr);
NSLog(#"Firstname - Lastname : %# - %#",
[NSMutableString stringWithFormat:#"%#",[dicr objectForKey:#"user_first_name"]],
[NSMutableString stringWithFormat:#"%#",[dicr objectForKey:#"user_last_name"]]);
}
}
}
You can see the Console output as below :
Firstname - Lastname : Chandra Bhusan - Pandey
Firstname - Lastname : Kalaiyarasan - Balu
Firstname - Lastname : (null) - (null)
Firstname - Lastname : Girija - S
Firstname - Lastname : Girija - S
Firstname - Lastname : (null) - (null)
I recommend and use TouchJSON for parsing JSON.
To answer your comment to Alex. Here's quick code that should allow you to get the fields like activity_details, last_name, etc. from the json dictionary that is returned:
NSDictionary *userinfo=[jsondic valueforKey:#"#data"];
NSDictionary *user;
NSInteger i = 0;
NSString *skey;
if(userinfo != nil){
for( i = 0; i < [userinfo count]; i++ ) {
if(i)
skey = [NSString stringWithFormat:#"%d",i];
else
skey = #"";
user = [userinfo objectForKey:skey];
NSLog(#"activity_details:%#",[user objectForKey:#"activity_details"]);
NSLog(#"last_name:%#",[user objectForKey:#"last_name"]);
NSLog(#"first_name:%#",[user objectForKey:#"first_name"]);
NSLog(#"photo_url:%#",[user objectForKey:#"photo_url"]);
}
}