Can't access to inner nodes in JSON message - IOS - objective-c

I'm trying to access "node" node for this JSON message:
{
"nodes": [
{
"node": {
"title": "Jornada del Fútbol Profesional contra el hambre",
"description": "
"image": "",
"fecha": "",
"nid": "",
"noticia_relacionada_1_path": "",
"noticia_relacionada_2_path": "",
"image_small_2": ""
}
}
]
}
With this code:
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *results = [responseString JSONValue];
NSDictionary *nodes = [results objectForKey:#"nodes"];
results dictionary has 1 key result. nodes dictionary has 10 keys result. But when I try to access for node with all of this options, I got no results:
NSString *node = [nodes valueForKey:#"node"];
NSArray *nodeArray = [nodes objectForKey:#"node"];
NSDictionary *nodeDic = [nodes objectForKey:#"node"];
Many thanks

The object you retrieve with
NSDictionary *nodes = [results objectForKey:#"nodes"];
is not a dictionary, it is an array of dictionaries, each with one entry with the key "node". To get the first node:
NSArray *nodes = [results objectForKey:#"nodes"];
NSDictionary firstNodeDict = [[nodes objectAtIndex: 0] objectForKey: #"node"];

Related

How to get array object values from JSON response?

I have a json response in this format please look at this.I want to get lat and long values for every address.
{
"message":"success",
"data":
{
"docs":
[
{
"_id":"573d8eca67c7f172cc88387e",
"user":
{
"phone":"8510932519)/+",
"image":"",
"name":"Niraj#%"
},
"distance":18825,
"bookingNumber":"42aopy2dyry8",
"bookingType":0,
"paymentMode":"Card",
"tip":0,
"estimatedFare":51.1,
"estimatedDuration":"2364",
"created":"2016-05-18T14:49:31.231Z",
"stop2":
{
"address":"Malviya Nagar, New Delhi, Delhi 110017, India",
"location":[28.533519700000003,77.21088569999999]
},
"stop1":
{
"address":"Ansari Nagar East, New Delhi, Delhi 110029, India",
"location":
[
28.566540099999997,
77.2098409
]
},
"destination":
{
"address":"Saket, New Delhi, Delhi 110017, India",
"location":
[
28.524578699999996,
77.206615
]
},
"currentLocation":
{
"address":"26, Ashok MargJ Block, Pocket J, Sector 18",
"location":
[
28.568437,
77.32404
]
}
}
],
"total":1,
"limit":8,
"page":":1",
"pages":1
}
}
i need to get lat and long for every address. i am using this code for get the address, but how will i get lat and long for 0 and 1 index in location array?
dictionary = [[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]objectForKey:#"data"];
NSArray *IDArray = [dictionary objectForKey:#"docs"];
for (NSDictionary *Dict in IDArray)
{
NSMutableDictionary *temp = [NSMutableDictionary new];
[temp setObject:[Dict objectForKey:#"_id"] forKey:#"_id"];
NSString *booknumber = [Dict objectForKey:#"bookingNumber"];
if([booknumber length] != 0)
[temp setObject:booknumber forKey:#"bookingNumber"];
NSMutableDictionary *stp1 = [Dict objectForKey:#"stop1"];
if ([[stp1 allKeys] containsObject:#"address"]) {
[temp setObject:[stp1 objectForKey:#"address"] forKey:#"address"];
}
NSMutableDictionary *stp2 = [Dict objectForKey:#"stop2"];
if ([[stp2 allKeys] containsObject:#"address"]) {
[temp setObject:[stp2 objectForKey:#"address"] forKey:#"address1"];
}
NSMutableDictionary *currentloc = [Dict objectForKey:#"currentLocation"];
if ([[currentloc allKeys] containsObject:#"address"]) {
[temp setObject:[currentloc objectForKey:#"address"] forKey:#"address1"];
}
try this
NSMutableDictionary *stp1 = [Dict objectForKey:#"stop1"];
if ([[stp1 allKeys] containsObject:#"address"]) {
[temp setObject:[stp1 objectForKey:#"address"] forKey:#"address"];
// take one Temp array for fetch lat and long
NSArray *tempstp1 = [stp1 objectForKey:#"location"];
[temp setObject:[tempstp1 objectAtIndex:0] forKey:#"latitude"];
[temp setObject:[tempstp1 objectAtIndex:1] forKey:#"longitude"];
}
NSMutableDictionary *stp2 = [Dict objectForKey:#"stop2"];
if ([[stp2 allKeys] containsObject:#"address"]) {
[temp setObject:[stp2 objectForKey:#"address"] forKey:#"address"];
// take one Temp array for fetch lat and long
NSArray *tempstp2 = [stp2 objectForKey:#"location"];
[temp setObject:[tempstp2 objectAtIndex:0] forKey:#"latitude"];
[temp setObject:[tempstp2 objectAtIndex:1] forKey:#"longitude"];
}

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);
}

Retrieve nested objects from JSON - Objective C

I seem to be having a small issue with the parsing through a nested JSON result. The following code works perfectly if the JSON is not nested. I'm a littler perplexed on how to proceed as every attempted (through examples of others) have failed.
So, to test this I'm using the following API from https://developer.worldweatheronline.com/page/explorer-free
I simply would like to get my current temperature (temp_c).
Below is the code calling the service. Note that I have an NSObject that will fill the data, but of course I can't seem to get to that stage. Also it is an NSMutableArray throughout. Again, I don't think that is the issue but provides context.
-(void)retrieveLocalWeatherService {
NSURL *url = [NSURL URLWithString:getLocalWeather];
NSData *data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
//set up array and json call
weatherArray = [[NSMutableArray alloc]init];
//Loop through the JSON array
for (int i = 0; i< jsonArray.count; i++)
{
//create our object
NSString *nTemp = [[jsonArray objectAtIndex:i]objectForKey:#"temp_C"];
NSString *nPressure = [[jsonArray objectAtIndex:i]objectForKey:#"pressure"];
NSString *nHumidity = [[jsonArray objectAtIndex:i]objectForKey:#"humidity"];
//Add the object to our animal array
[weatherArray addObject:[[LocalWeather alloc]initWithtemp:(nTemp) andpressure:nPressure andhumidity:nHumidity]];
}
Here is the JSON response.
{
"data": {
"current_condition": [
{
"cloudcover": "75",
"FeelsLikeC": "31",
"FeelsLikeF": "88",
"humidity": "70",
"observation_time": "05:15 AM",
"precipMM": "0.0",
"pressure": "1011",
"temp_C": "28",
"temp_F": "82",
"visibility": "10",
"weatherCode": "116",
"weatherDesc": [
{
"value": "Partly Cloudy"
}
],
"weatherIconUrl": [
{
"value": "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0002_sunny_intervals.png"
}
],
"winddir16Point": "N",
"winddirDegree": "10",
"windspeedKmph": "41",
"windspeedMiles": "26"
}
],
"request": [
{
"query": "Brisbane, Australia",
"type": "City"
}
],
I cut off the JSON service as it goes for miles, so where am I going wrong? I believe its somewhere within "for-loop" but am unsure where. I know its major node is "data" and then sub-node is "current_condition". Should I be digging through the JSON results? If what is the best approach.
BTW, I'm getting a response from the server with the entire JSON result..clearly a parsing issue on my part.
Thanks in advance!
please be kind i'm a newbie.
You are parsing your JSON data in wrong way, you are parsing JSON directly to Array but as per your JSON format your JSON will return an NSDictionary not NSArray.
-(void)retrieveLocalWeatherService {
NSURL *url = [NSURL URLWithString:getLocalWeather];
NSData *data = [NSData dataWithContentsOfURL:url];
NSDictionary *weatherJson = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSArray *currentConditionArray = [weatherJson valueForKeyPath:#"Data.current_condition"];
//set up array and json call
weatherArray = [[NSMutableArray alloc]init];
//Loop through the JSON array
for (NSDictionary *item in currentConditionArray)
{
//create our object
NSString *nTemp = [item objectForKey:#"temp_C"];
NSString *nPressure = [item objectForKey:#"pressure"];
NSString *nHumidity = [item objectForKey:#"humidity"];
//Add the object to our animal array
[weatherArray addObject:[[LocalWeather alloc]initWithtemp:(nTemp) andpressure:nPressure andhumidity:nHumidity]];
}
}

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?

How do I parse JSON with Objective-C?

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"]);
}
}