JSON Parsing. value not comes in Kilometers - iphone

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

Related

Need help for parsing JSON

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

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 json parse with components Separated By String

im new to parsing JSON and im trying a simple task, to retrieve a URL from a forecast weather json file.
Here i parse the json and i NSLog the contents of each component of the data:
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&myError];
NSArray *data = [res objectForKey:#"data"];
NSLog(#"data=%#",data);
NSArray *results = [data valueForKey:#"weather"];
NSLog(#"weather=%#",results);
NSArray *results1 = [results valueForKey:#"tempMaxC"];
NSLog(#"tempMaxC=%#",results1);
NSArray *results2 = [results1 valueForKey:#"weatherIconUrl"];
NSLog(#"weatherIconUrl=%#",results2);
The problem is that when i get the WeatherIconUrl it comes with this format
"http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png"
and i cant get the url itself without the quotation marks, i tried using nsrange and componentsSeparatedByString but it always gives me this error:
[__NSArrayI componentsSeparatedByString:]: unrecognized selector sent to instance
JSON from server:
{
"data": {
"current_condition": [
{
"cloudcover": "0",
"humidity": "73",
"observation_time": "12:19 PM",
"precipMM": "0.0",
"pressure": "1021",
"temp_C": "23",
"temp_F": "73",
"visibility": "10",
"weatherCode": "113",
"weatherDesc": [
{
"value": "Sunny"
}
],
"weatherIconUrl": [
{
"value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png"
}
],
"winddir16Point": "NW",
"winddirDegree": "320",
"windspeedKmph": "17",
"windspeedMiles": "11"
}
],
"request": [
{
"query": "Fanzeres, Portugal",
"type": "City"
}
],
"weather": [
{
"date": "2012-09-12",
"precipMM": "0.0",
"tempMaxC": "28",
"tempMaxF": "83",
"tempMinC": "17",
"tempMinF": "63",
"weatherCode": "113",
"weatherDesc": [
{
"value": "Sunny"
}
],
"weatherIconUrl": [
{
"value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png"
}
],
"winddir16Point": "NW",
"winddirDegree": "312",
"winddirection": "NW",
"windspeedKmph": "16",
"windspeedMiles": "10"
},
{
"date": "2012-09-13",
"precipMM": "0.0",
"tempMaxC": "33",
"tempMaxF": "91",
"tempMinC": "17",
"tempMinF": "63",
"weatherCode": "113",
"weatherDesc": [
{
"value": "Sunny"
}
],
"weatherIconUrl": [
{
"value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png"
}
],
"winddir16Point": "N",
"winddirDegree": "8",
"winddirection": "N",
"windspeedKmph": "10",
"windspeedMiles": "6"
}
]
}
}
Sorry for my bad english and please correct me if im doing this wrong, thanks in advance
use objectForKey instead of valueForKey when getting the array from #"weatherIconUrl" then get the string into NSString e.g.
NSString *weatherIconUrlString = [results2 objectAtIndex:0]
to check that this is a valid url, use the canHandleRequest method of NSURLConnection, e.g.
NSURL *url = [NSURL URLWithString:weatherIconUrlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url
BOOL canGo = [NSURLConnection canHandleRequest:request];
If you truly have quotes surrounding your URL, then try something like this:
NSString *someURLString = [results2 objectAtIndex:0];
NSString *quotesRemoved = [someURLString stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#"\""]];
putting the server's output through jsonLint.com gives an easier to read format of the json.
The code below now gets the weather icon url as required. It assumes the json has been downloaded as an NSData object called jsonData, and doesn't check for which date the data refers to.
NSError *error = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves
error:&error];
NSArray *data = [jsonDict valueForKey:#"data"];
NSArray *weather = [data valueForKey:#"weather"];
NSArray *weatherIcon = [[weather objectAtIndex:0] valueForKey:#"weatherIconUrl"];
NSString *url = [[weatherIcon objectAtIndex:0] valueForKey:#"value"];
The resulting url is used in an NSURLRequest and shown in a webview

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

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