Need help for parsing JSON - iphone

I'm learning how to parse JSON. I've made the raywenderlich tutorial but I'm still lost with some steps. I got my own JSON :
{
"Albumvideo":{
"album01":{
"titreAlbum":"Publicité",
"photoAlbum":"blabla.jpg",
"pubVideos":{
"pub01":[
{
"titrePub":"Chauffage Compris",
"dureePub":"01'25''",
"photoPub":"chauffage.jpg",
"lienPub":"http://www.wmstudio.ch/videos/chauffage.mp4"
}
]
}
},
"album02":{
"titreAlbum":"Events",
"photoAlbum":"bloublou.jpg",
"eventsVideos":{
"event01":[
{
"titreEvent":"Chauffage Compris",
"dureeEvent":"01'25''",
"photoEvent":"chauffage.jpg",
"lienEvent":"http://www.wmstudio.ch/videos/chauffage.mp4"
}
]
}
}
}
}
The I got my 'Code' to parse my JSON :
- (void) viewDidLoad
{
[super viewDidLoad];
dispatch_async (kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:lienAlbumsVideo];
[self performSelectorOnMainThread:#selector(fetchedData:)withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSArray* albumsVideo = [json objectForKey:#"Albumvideo"];
NSLog(#"Nombre d'albums : %i",[albumsVideo count]);
}
This works fine, my NSLog returns '2'. Where I now have difficulties is to make an array with "titreAlbum" or "event01" for example. If I do :
NSArray* event01 = [json objectForKey:#"event01"];
NSLog(#"Number of objects in event01 : %i ", [event01 count]);
My NSLog returns '0'.
I didn't really understand how to parse information from multidimensional array in a JSON. Thank's already!
Nicolas

You do not have a two-dimensional array. And JSON does not support this, but arrays of array (as C does and as Objective-C does).
NSDictionary *document = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
// Getting titreAlbum
NSDictionary *albumVideo = document[#"Albumvideo"];
NSDictionary *album01 = albumVideo[#"album01"];
NSString *titreAlbum = album01[#"titreAlbum"];
// Getting an event
NSDictionary *album02 = albumVideo[#"album02"];
NSDictionary *eventVideos = album02[#"eventsVideos"];
NSArray *event01 = eventVideo[#"event01"];
(Typped in Safari)
You can use KVC, too, if you are not interested in the middle layers.
But your identifiers and question let me think, that the structure of your JSON is malformed.

Some things,
every time you see
{ ... }
in the json that is the beginning/end of an NSDictionary
once parsed, while
[ ... ]
is the beginning end of an NSArray.
So once you parse the json using NSJSONSerialization you can navigate that dictionary using that knowledge.
Given the json you have to get an array of "titreAlbum" you would have to do something like:
NSDictionary *albumVideo = json[#"Albumvideo"];
NSMutableArray *albumTitres = [[NSMutableArray alloc] init];
for (NSDictionary *album in albumVideo) {
[albumTitres addObject:album[#"titreAlbum"]];
}
That said, I think your json is not malformed as is passing the JSONLint validation, but is not helping you to parse it. I would expect that the Albumvideo is an array of albums, instead of a dictionary of albums.

I had the same issue. I was actually trying to access Google Distance API where i needed to get
{
"routes" : [
{
"bounds" : {
"northeast" : {
"lat" : 23.0225066,
"lng" : 73.2544778
},
"southwest" : {
"lat" : 19.0718263,
"lng" : 72.57129549999999
}
},
"copyrights" : "Map data ©2014 Google",
"legs" : [
{
"distance" : {
"text" : "524 km",
"value" : 523839
},
"duration" : {
"text" : "7 hours 34 mins",
"value" : 27222
},
"end_address" : "Mumbai, Maharashtra, India",
"end_location" : {
"lat" : 19.0759856,
"lng" : 72.8776573
},
"start_address" : "Ahmedabad, Gujarat, India",
"start_location" : {
"lat" : 23.0225066,
"lng" : 72.57129549999999
},
"steps" : [
{
"distance" : {
"text" : "0.2 km",
"value" : 210
},
"duration" : {
"text" : "1 min",
"value" : 25
},
"end_location" : {
"lat" : 23.0226436,
"lng" : 72.573224
},
"html_instructions" : "Head on Swami Vivekananda RdRoad/Swami Vivekananda Rd",
"polyline" : {
"points" : "uqokCsa}yLS?GYEk#Cq##qA#eA#aADm#"
},
"start_location" : {
"lat" : 23.0225066,
"lng" : 72.57129549999999
},
"travel_mode" : "DRIVING"
}]`
I needed to access routes.legs.steps.html_instructions.
So my code is as under
NSURL *url=[[NSURL alloc] initWithString:[NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=ahmedabad&destination=%#",self.city]];`
NSURLResponse *res;
NSError *err;
NSData *data=[NSURLConnection sendSynchronousRequest:[[NSURLRequest alloc] initWithURL:url] returningResponse:&res error:&err];
NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSArray *routes=dic[#"routes"];
NSArray *legs=routes[0][#"legs"];
NSArray *steps=legs[0][#"steps"];
NSMutableArray *textsteps=[[NSMutableArray alloc] init];
NSMutableArray *latlong=[[NSMutableArray alloc]init];
for(int i=0; i< [steps count]; i++){
NSString *html=steps[i][#"html_instructions"];
[latlong addObject:steps[i][#"end_location"]];
[textsteps addObject:html];
}

Related

How to parse my JSON data in IOS5

Can anyone tell me how to parse my json data in IOS5. I'm providing my JSON data below:
{
"fieldType" : "Alphanumeric",
"fieldName" : "Name"
},{
"fieldType" : "Numeric",
"fieldName" : "Card Num"
},{
"fieldType" : "Alphanumeric",
"fieldName" : "Pin Num"
}
Also is this JSON format correct or do I need to change the JSON format? When I try to parse JSON using below code I get an error:
The operation couldn’t be completed. (Cocoa error 3840.)
The code I'm using:
NSError *error = nil;
NSData *jsonData = [filedList dataUsingEncoding:[NSString defaultCStringEncoding]];
if (jsonData)
{
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
if (error)
{
NSLog(#"error is %#", [error localizedDescription]);
// Handle Error and return
return;
}
NSArray *keys = [jsonObjects allKeys];
// values in foreach loop
for (NSString *key in keys)
{
NSLog(#"%# is %#",key, [jsonObjects objectForKey:key]);
}
}
else
{
// Handle Error
}
The JSON data is not correctly formatted. Since you have an array of items, you need to enclose this in [ ... ]:
[
{
"fieldType" : "Alphanumeric",
"fieldName" : "Name"
},{
"fieldType" : "Numeric",
"fieldName" : "Card Num"
},{
"fieldType" : "Alphanumeric",
"fieldName" : "Pin Num"
}
]
Now JSONObjectWithData gives you an NSMutableArray of NSMutableDictionary objects (because of the NSJSONReadingMutableContainers flag).
You can walk through the parsed data with
for (NSMutableDictionary *dict in jsonObjects) {
for (NSString *key in dict) {
NSLog(#"%# is %#",key, [dict objectForKey:key]);
}
}
In any type of parsing, first of all NSLog the JSON or XML string then start writing your parsing your code.
In your case as per the JSON string you mentioned its a array of dictionaries, and once you got your jsonObjects do this to get your data..
id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"%#",jsonObjects);
// as per your example its an array of dictionaries so
NSArray* array = (NSArray*) jsonObjects;
for(NSDictionary* dict in array)
{
NSString* obj1 = [dict objectForKey:#"fieldType"];
NSString* obj2 = [dict objectForKey:#"fieldName"];
enter code here
enter code here
}
In this way you can parse the your json string.. for more details go through this tutorial by Raywenderlich.

How to implement code for getting latitude and longitude?

Hi all, how to get latitude and longitude values of location? I am trying using below code but I am getting wrong response, I need your help to solve the problem.
- (CLLocationCoordinate2D) geoCodeUsingAddress:(NSString *)address
{
NSString *city,*state,*zip;
city=#"Hyderabad";
state=#"Andrapradesh";
zip=#"22345";
address=city,state,zip;
NSLog(#"##########%#",address);
double latitude = 0, longitude = 0;
NSString *esc_addr = [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *req = [NSString stringWithFormat:#"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%#", esc_addr];
NSString *result = [NSString stringWithContentsOfURL:[NSURL URLWithString:req] encoding:NSUTF8StringEncoding error:NULL];
NSLog(#"333333%#",result);
if (result) {
NSScanner *scanner = [NSScanner scannerWithString:result];
NSLog(#"##########%#",scanner);
if ([scanner scanUpToString:#"\"lat\":" intoString:nil] && [scanner scanString:#"\"lat\":" intoString:nil]) {
[scanner scanDouble:&latitude];
NSLog(#"4444444%#",scanner);
NSLog(#"5555%#",latitude);
if ([scanner scanUpToString:#"\"lng\":" intoString:nil] && [scanner scanString:#"\"lng\":" intoString:nil]) {
[scanner scanDouble:&longitude];
NSLog(#"6666%#",scanner);
NSLog(#"7777%#",longitude);
}
}
}
CLLocationCoordinate2D center;
center.latitude = latitude;
NSLog(#"##########%#",latitude);
center.longitude = longitude;
return center;
}
333333 {
"results" : [
{
"address_components" : [
{
"long_name" : "Hyderabad",
"short_name" : "Hyderabad",
"types" : [ "locality", "political" ]
},
{
"long_name" : "Ranga Reddy",
"short_name" : "R.R. District",
"types" : [ "administrative_area_level_2", "political" ]
},
{
"long_name" : "Andhra Pradesh",
"short_name" : "Andhra Pradesh",
"types" : [ "administrative_area_level_1", "political" ]
},
{
"long_name" : "India",
"short_name" : "IN",
"types" : [ "country", "political" ]
}
],
"formatted_address" : "Hyderabad, Andhra Pradesh, India",
"geometry" : {
"bounds" : {
"northeast" : {
"lat" : 17.57944810,
"lng" : 78.69135810
},
"southwest" : {
"lat" : 17.23837080,
"lng" : 78.24014110
}
},
"location" : {
"lat" : 17.3850440,
"lng" : 78.4866710
},
"location_type" : "APPROXIMATE",
"viewport" : {
"northeast" : {
"lat" : 17.55533690,
"lng" : 78.74278980
},
"southwest" : {
"lat" : 17.21459250,
"lng" : 78.23055219999999
}
}
},
"types" : [ "locality", "political" ]
}
],
"status" : "OK"
}
2012-03-29 23:56:58.577 SVGeocoder[670:11603]
####
2012-03-29 23:56:58.578 SVGeocoder[670:11603] ##########(null)
Try this:
- (CLLocationCoordinate2D) geoCodeUsingAddress: (NSString *) address
{
CLLocationCoordinate2D myLocation;
NSString *esc_addr = [address stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSString *req = [NSString stringWithFormat: #"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%#", esc_addr];
NSDictionary *googleResponse = [[NSString stringWithContentsOfURL: [NSURL URLWithString: req] encoding: NSUTF8StringEncoding error: NULL] JSONValue];
NSDictionary *resultsDict = [googleResponse valueForKey: #"results"];
NSDictionary *geometryDict = [resultsDict valueForKey: #"geometry"];
NSDictionary *locationDict = [geometryDict valueForKey: #"location"];
NSArray *latArray = [locationDict valueForKey: #"lat"]; NSString *latString = [latArray lastObject];
NSArray *lngArray = [locationDict valueForKey: #"lng"]; NSString *lngString = [lngArray lastObject];
myLocation.latitude = [latString doubleValue];
myLocation.longitude = [lngString doubleValue];
LogInfo(#"lat: %f\tlon:%f", myLocation.latitude, myLocation.longitude);
return myLocation;
}

JSON Parsing. value not comes in Kilometers

i am new programmer.i am using Google Matrix API. i get the following response i wants fetch "text" : "1686 km". i am using Json Parsing. Thanks
"destination_addresses" : [ "San Francisco, Californie, États-Unis" ],
"origin_addresses" : [ "Vancouver, BC, Canada" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "1 686 km",
"value" : 1685690
},
"duration" : {
"text" : "3 jours 21 heures",
"value" : 336418
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
SBJsonParser *json = [[SBJsonParser new] autorelease];
NSError *jsonError;
parsedJSON = [json objectWithString:data error:&jsonError];
Well, parsedJSON will be an NSDictionary so:
NSArray *rows = [parsedJSON objectForKey:#"rows"];
for (NSDictionary *row in rows) {
NSArray *elements = [row objectForKey:#"elements"];
for (NSDictionary *element in elements) {
NSDictionary *distance = [element objectForKey:#"distance"];
NSString *kmDistance = [distance objectForKey:#"text"]; ///< That's what you wanted
}
}

iPhone:Issues when formatting json for server request

I need to make the json params like below.
Final output should be,
{"submissionTime":"\/Date(1331549630849)\/",
"statusId":"0",
"answers":[{"answer":"Yes","qid":167},{"answer":"Hello","qid":168}],
"participantId":"16369",
"token":"t_ikHOXVjlcsSb9Tfdn5RaO54JGQobHodUD5881SKevxy63jwLxe8ZPQvXYss4pR"}
I am trying to make this format. I got the time, statusid, participantid and token. Its fine. But, i am facing problem when making "answers" array.
I use the below code for making the answers json format like below.
NSArray *answerkeys = [NSArray arrayWithObjects:#"answer", #"qid",nil];
NSString *qID = [NSString stringWithFormat:#"%d", [questionidArray objectAtIndex:i] ]; // for loop
NSArray *objectkeys = [NSArray arrayWithObjects:value, qID,nil];
NSString *answerjsonRequest = [pSr makeJSONObject:objectkeys :answerkeys];
answerjsonRequest = [(NSString *)answerjsonRequest stringByReplacingOccurrencesOfString:#"\n" withString:#""];
[textvaluesArray addObject:[NSString stringWithFormat:#"%#", answerjsonRequest]];
and the output is like below.
(
"{ \"answer\" : \"Hello\", \"qid\" : \"220421824\"}",
"{ \"answer\" : \"How are you\", \"qid\" : \"115781136\"}"
)
But, when i am adding all in one in the final output like below,
NSString *jsonRequest = [pSr makeJSONObject:[NSArray arrayWithObjects: participantID, (NULL!=textvaluesArray)?textvaluesArray:#"0", [NSString stringWithFormat:#"%d", statusID], subTime, [appDelegate getSessionToken], nil] :[NSArray arrayWithObjects:#"participantId", #"answers", #"statusId", #"submissionTime", #"token", nil] ];
The final json result is this.
{
"submissionTime" : "\/Date(1331566698)\/",
"token" : "t_hvYoxifLQhxEKfyw1CAgVtgOfA3DjeB9jZ3Laitlyk9fFdLNjJ4Cmv6K8s58iN",
"participantId" : "16371",
"answers" : [
"{ \"answer\" : \"Hello\", \"qid\" : \"220421824\"}",
"{ \"answer\" : \"Hello\", \"qid\" : \"115781136\"}"
],
"statusId" : "0"
}
BUT, this is NOT the one what i want. My expected JSON output is top above mentioned. I tried many ways, but couldn't achieve this. Could someone helping me on this to resolve to get the exact JSON output?
Thank you!
I ran into this issue as well, and created a quick category to take care of the problem.
#interface NSString (ReplaceForJSON)
- (NSString*)replaceEscapedQuotes;
#end
#implementation NSString (ReplaceForJSON)
- (NSString*)replaceEscapedQuotes
{
NSString* returnVal = [self stringByReplacingOccurrencesOfString:#"\\\"" withString:#"\""];
returnVal = [returnVal stringByReplacingOccurrencesOfString:#"\"{" withString:#"{"];
returnVal = [returnVal stringByReplacingOccurrencesOfString:#"}\"" withString:#"}"];
return returnVal;
}
#end

How to handle JSON response using SBJSON iPhone?

I am receiving the below response from my web service?
Can any one has idea how to handle it using SBJSON?
{
"match_details" :
{
"score" : 86-1
"over" : 1.1
"runrate" : 73.71
"team_name" : England
"short_name" : ENG
"extra_run" : 50
}
"players" :
{
"key_0" :
{
"is_out" : 2
"runs" : 4
"balls" : 2
"four" : 1
"six" : 0
"batsman_name" : Ajmal Shahzad *
"wicket_info" : not out
}
"key_1" :
{
"is_out" : 1
"runs" : 12
"balls" : 6
"four" : 2
"six" : 0
"batsman_name" : Andrew Strauss
"wicket_info" : c. Kevin b.Kevin
}
"key_2" :
{
"is_out" : 2
"runs" : 20
"balls" : 7
"four" : 4
"six" : 0
"batsman_name" : Chris Tremlett *
"wicket_info" : not out
}
}
"fow" :
{
"0" : 40-1
}
}
I have done something like this:
Import SBJSON/JSON.h header file and do something like this ...
NSString *jsonResponseString = ...your JSON response...;
NSDictionary *jsonDictionary = [jsonResponseString JSONValue];
NSDictionary *players = [jsonDictionary objectForKey:#"players"];
NSDictionary *player = [players objectForKey:#"key_0"];
NSLog( #"%# %# %# %# %# %# %#", [player objectForKey:#"is_out"],
[player objectForKey:#"runs"], [player objectForKey:#"balls"],
[player objectForKey:#"four"], [player objectForKey:#"six"],
[player objectForKey:#"batsman_name"], [player objectForKey:#"wicket_info"] );
... etc.
Here is how to get the response as an array. But the main question is: What do you want to do with your data? ;)
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSString * response = [request responseString];
NSMutableArray *array = [parser objectWithString:response error:nil];
NSMutableArray *match = [array valueForKey:#"match_details"];
NSMutableArray *players = [array valueForKey:#"players"];
// This should display your players name
for(id player in players) {
NSLog(#"Player name: %#", [(NSDictionary *)player valueForKey:#"batsman_name"]);
}