I am trying to parse the JSON result from Mapquest geocode API.
NSDictionary *JSONReponseDic = [NSJSONSerialization JSONObjectWithData:mapquestdata options:0 error:&error];
NSMutableArray *resultsArray = [JSONReponseDic objectForKey:#"results"];
NSDictionary *locationDic = [resultsArray objectAtIndex:0];
NSLog(#"loc dic %#", locationDic);
NSString *city = [locationDic objectForKey:#"adminArea5"];
NSLog(#"city : %#", city);
I can parse until locationDic, which returns
loc dic {
locations = (
{
adminArea1 = US;
adminArea1Type = Country;
adminArea3 = CA;
adminArea3Type = State;
adminArea4 = "Santa Clara County";
adminArea4Type = County;
adminArea5 = "Los Altos";
adminArea5Type = City;
displayLatLng = {
lat = "37.37964";
lng = "-122.11877";
};
dragPoint = 0;
geocodeQuality = POINT;
geocodeQualityCode = P1AAA;
latLng = {
lat = "37.37949";
lng = "-122.11903";
};
linkId = 0;
mapUrl = "http://www.mapquestapi.com/staticmap/v4/getmap?key=Fmjtd|luub206tl1,rg=o5-9ubah0&type=map&size=225,160&pois=purple-1,37.37949,-122.11903,0,0|¢er=37.37949,-122.11903&zoom=15&rand=-159915059";
postalCode = "94022-2707";
sideOfStreet = R;
street = "145 1st St";
type = s;
}
);
providedLocation = {
location = "145 1st St,Los Altos, CA 94022";
};
}
Then, when I am trying to get the city name, the log returns null. Am I parsing this the right way?
It should be [locationDic valueForKeyPath:#"locations.adminArea5"];.
Related
I need to get particular values from below JSON response, The values are I have mentioned below
Reg no: (Need to show callout)
Lat : (Need to use drop pin on map)
Long : (Need to use drop pin on map)
Name : (Need to show callout)
Age : (Need to show callout)
NOTE : The school of array values getting from server so It will Increase based on A , B and C categories. Its not static!
{
A = {
school = (
{
reg_no = 1;
latitude = "22.345";
longitude = "-12.4567";
student = (
{
name = "akila";
age = "23";
}
);
city = "<null>";
state = TN;
},
{
reg_no = 2;
latitude = "22.345";
longitude = "-12.4567";
student = (
{
name = "sam";
age = "23";
}
);
city = "<null>";
state = TN;
}, {
reg_no = 3;
latitude = "22.345";
longitude = "-12.4567";
student = (
{
name = "lansi";
age = "23";
}
);
city = "<null>";
state = TN;
}
);
Schoolname = "Good School";
categories = school;
};
}
My Code (Below code not working) :
if (data) {
NSError *error;
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:&error];
NSDictionary *response = JSON[#"response"];
for (NSDictionary *entry in response[#"A"][#"school"]) {
NSString *regNo = entry[#"reg_no"];
NSString *name = entry[#"student"][#"name"];
NSString *age = entry[#"student"][#"age"];
double latitude = [entry[#"latitude"] doubleValue];
double longitude = [entry[#"longitude"] doubleValue];
MKPointAnnotation *myAnnotation = [[MKPointAnnotation alloc] init];
myAnnotation.coordinate = CLLocationCoordinate2DMake(latitude, longitude);
myAnnotation.title = name;
myAnnotation.subtitle = [NSString stringWithFormat:#"Reg: %#, Age: %#", regNo, age];
[mapView addAnnotation:myAnnotation];
}
Try NSJSONSerialization
NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];
if (!jsonArray) {
NSLog(#"Error parsing JSON: %#", e);
} else {
for(NSDictionary *item in jsonArray) {
NSLog(#"Item: %#", item);
}
}
You can use NSJSONSerialization to parse the JSON, then you can access the values you need in a loop using Objective-C's subscripting syntax. Once you have all these, you can add the entries as MKAnnotations on an MKMapView to get what you want. Note that MKAnnotation is a protocol, so you'll need to create a class that implements it.
MKMapView *mapView = [MKMapView new];
NSDictionary *parsedJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
for (NSDictionary *entry in parsedJSON[#"A"][#"school") {
NSString *regNo = entry[#"reg_no"];
NSString *name = entry[#"student"][#"name"];
NSString *age = entry[#"student"][#"age"];
double latitude = [entry[#"latitude"] doubleValue];
double longitude = [entry[#"longitude"] doubleValue];
id<MKAnnotation> annotation = [/*class implementing MKAnnotation*/ new];
annotation.coordinate = CLLocationCoordinate2DMake(latitude, longitude);
annotation.title = name;
annotation.subtitle = [NSString stringWithFormat:#"Reg: %#, Age: %#", regNo, age];
[mapView addAnnotation:annotation];
}
u should iterate entry[#"student"] to get the data of every student
entry[#"student"][#"name"] will get no data even if entry[#"student"] only have one
Your JSON file that you have provided for lacks of 'response' key in it. However, you are searching as NSDictionary *response = JSON[#"response"];. That could be the problem. Other than this, you can try NSDictionary's valueForKey: method to search deeper in your JSON.
{
Address = (
{
address = "Bengaluru, Karnataka 560008, India";
"address_id" = 29;
"address_title" = "";
"building_name" = "";
latitude = "23.95579108";
longitude = "77.64169808";
"user_id" = 13;
},
{
address = "Bengaluru, Karnataka 560008, India";
"address_id" = 31;
"address_title" = "";
"building_name" = "";
latitude = "22.95578162";
longitude = "77.64173089";
"user_id" = 13;
},
{
address = "Bengaluru, Karnataka 560008, India";
"address_id" = 37;
"address_title" = "";
"building_name" = "";
latitude = "22.95577373";
longitude = "77.64173507";
"user_id" = 13;
},
{
address = "256, Road Number 19, Wadla Village, Vadala, Mumbai, Maharashtra 400031, India";
"address_id" = 49;
"address_title" = dsa;
"building_name" = das;
latitude = "19.01761470";
longitude = "72.85616440";
"user_id" = 13;
}
);
}
I'm trying to retrive data from the JSON dictionary.
I need to fetch the datas in address from the Address dictionary and store it in an array .
My Array should look like this :
[Bengaluru, Karnataka 560008, India,Bengaluru, Karnataka 560008, India,Bengaluru, Karnataka 560008, India,256, Road Number 19, Wadla Village, Vadala, Mumbai, Maharashtra 400031, India]
Need help please .
NSMutableArray *resultArray = [NSMutableArray new];
NSError *jsonError = [[NSError alloc] init];
NSDictionary *pR = [NSJSONSerialization JSONObjectWithData:yourJsonObject options:NSJSONReadingAllowFragments error:&jsonError];
NSArray *pArray = pR[#"Address"];
for(NSDictionary *dict in pR)
{
[resultArray addObject:dict[#"address"]];
}
Filtering NSDictionary with predicate
You can filter an NSDictionary with an NSPredicate.
Assuming your dictionary is NSDictionary *dict
NSArray *resultArray = [[dict objectForKey:#"Address" allValues] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"(key == %#)", #"address"]];
I'm able to retrieve data from the weather map api, however I can't figure out how to exactly parse the data. I'm able to do it only for a certain part of it.
This is the JSON data:
{
base = "cmc stations";
clouds = {
all = 56;
};
cod = 200;
coord = {
lat = "29.66";
lon = "-82.3";
};
dt = 1403641995;
id = 4156404;
main = {
humidity = 74;
pressure = 1018;
temp = "304.08";
"temp_max" = "306.48";
"temp_min" = "302.15";
};
name = Gainesville;
rain = {
3h = 0;
};
sys = {
country = US;
message = "0.2087";
sunrise = 1403605821;
sunset = 1403656392;
};
weather = (
{
description = "broken clouds";
icon = 04d;
id = 803;
main = Clouds;
}
);
wind = {
deg = 153;
gust = "1.54";
speed = "0.51";
};
}
Now I am able to get only one part of it :
base = "cmc stations"
like this:
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSLog(#"values %#",json);
NSLog(#"Checking values ------------ %#",[json objectForKey:#"cloud"]);
}
But when I try to do the same for other fields like
clouds
coord
main
I can't. I get a null value.
I'm guessing I need an additional NSDictionary or NSArray but just not sure how to go about it. Can someone please tell how can I do this? I'm mainly looking to get data from the main block :
humidity
temp
temp_max
temp_min
rain
sunrise
sunset
I think I have found a solution:
Here's how I'm getting the data:
NSString* base = [json objectForKey:#"base"];
NSLog(#"Value of first base variable: %#",base);
// NSArray* base = [json objectAtIndex:0];
NSArray *clouds = [json objectForKey:#"clouds"];
NSLog(#"Value of first clouds‹ variable: %#",clouds);
NSArray *coord = [json objectForKey:#"coord"];
NSLog(#"Value of first coord variable: %#",coord);
NSDictionary *main = [json objectForKey:#"main"];
NSLog(#"Value of first coord variable: %#",main);
NSArray* humidity = [main objectForKey:#"humidity"];
NSLog(#"humidity levels found manually : %#",humidity);
NSArray* temp_max = [main objectForKey:#"temp_max"];
NSLog(#"max temp levels found manually : %#",temp_max);
The problem is that most of those values are dictionaries, not arrays. When you see { } and colons (:) that will generally indicate the presence of a dictionary of key-value pairs, even though some of them may only have one such pair which might make it appear like an array or a stand-alone object.
To get clouds for instance:
NSDictionary *clouds = [json objectForKey:#"clouds"];
NSNumber *allClouds = [clouds objectForKey:#"all"];
NSLog(#"Value of first clouds‹ variable: %#",allClouds);
To get coord:
NSDictionary *coords = [json objectForKey:#"coord"];
NSNumber *lon = [coords objectForKey:#"lon"];
NSNumber *lat = [coords objectForKey:#"lat"];
NSLog(#"Value of lon is: %#",lon);
Well I guess its an easy question (because I am only learning IOS recently).
Most of the tutorials that I have seen show simple JSON key value examples.
However I am looking a JSON structure which has the following format:
So I have lets say a JSON page that displays something like:
loans: (
{
activity = "Personal Products Sales";
"basket_amount" = 0;
"bonus_credit_eligibility" = 1;
"borrower_count" = 1;
description = {
languages = (
en
);
};
"funded_amount" = 0;
id = 623727;
image = {
id = 1457061;
"template_id" = 1;
};
"loan_amount" = 475;
location = {
country = Philippines;
"country_code" = PH;
geo = {
level = country;
pairs = "13 122";
type = point;
};
town = "Maasin City, Leyte";
};
name = Zita;
"partner_id" = 145;
"planned_expiration_date" = "2013-11-28T21:00:02Z";
"posted_date" = "2013-10-29T21:00:02Z";
sector = Retail;
status = fundraising;
use = "to buy additional stocks of soap, toothpaste, dish washing products, etc.";
},
So for example if I want to extract the name I understand the key pair ideas so I just do something like:
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* latestLoans = [json objectForKey:#"loans"]; //2
NSDictionary* loan = [latestLoans objectAtIndex:0];
NSString *name = [loan objectForKey:#"name"];
And then *name should evaluate to : Zita.
But my question is ....
1) What wizardry do I need to do in order to get access data deep inside the structure like "level = country;" (the level is located inside "geo" which is located inside "location")
Can someone explain how to do this ?
Exactly the same way as you're doing right now :)
NSDictionary* loan = [latestLoans objectAtIndex:0];
NSDictionary* location = [loan objectForKey:#"location"];
NSDictionary* geo = [locationobjectForKey:#"geo"];
NSString* level = [geo objectforKey:#"country"];
or shorter:
NSDictionary* loan = [latestLoans objectAtIndex:0];
NSString* level = loan[#"location"][#"geo"][#"level"];
I am downloading a users timeline for my iOS app. Right now I am getting the full JSON response from Twitter's API URL https://api.twitter.com/1.1/statuses/home_timeline.json
It is returning everything as shown here...
Timeline response: (
{
contributors = "<null>";
coordinates = "<null>";
"created_at" = "Sat Jun 08 03:59:36 +0000 2013";
entities = {
hashtags = (
);
symbols = (
);
urls = (
{
"display_url" = "vine.co/v/bLrw1IjLKVl";
"expanded_url" = "https://vine.co/v/bLrw1IjLKVl";
indices = (
36,
59
);
url = "https://t.co/8yHzCzMFHC";
}
);
"user_mentions" = (
);
};
"favorite_count" = 3;
favorited = 0;
geo = "<null>";
id = 343215709989507073;
"id_str" = 343215709989507073;
"in_reply_to_screen_name" = "<null>";
"in_reply_to_status_id" = "<null>";
"in_reply_to_status_id_str" = "<null>";
"in_reply_to_user_id" = "<null>";
"in_reply_to_user_id_str" = "<null>";
lang = en;
place = "<null>";
"possibly_sensitive" = 0;
"retweet_count" = 1;
retweeted = 0;
source = "Vine - Make a Scene";
text = "Black people neighborhoods at night https://t.co/8yHzCzMFHC";
truncated = 0;
user = {
id = 1129039734;
"id_str" = 1129039734;
};
}
)
But I only want the "text" parameter. How do I only get the text of the tweets?
Thanks!
-Henry
Implement a JSON Parser that parses out what you need and discards the rest, for example yajl. There are plenty of examples. Yajl is fast...
The ugly solution would be to use the NSString message: componentsSeparatedByString to split the NSString containing your json on "text = " and then on "truncated = " to get the text in between...
Using NSJSONSerialization, there is an excellent example for twitter here
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL
URLWithString:#"http://api.twitter.com/1/statuses/user_timeline.json?
screen_name=xx"]];
NSData *response = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
NSError *jsonParsingError = nil;
NSArray *publicTimeline = [NSJSONSerialization JSONObjectWithData:response
options:0 error:&jsonParsingError];
NSDictionary *tweet;
for(int i=0; i<[publicTimeline count];i++)
{
tweet= [publicTimeline objectAtIndex:i];
NSLog(#”Statuses: %#”, [tweet objectForKey:#"text"]);
}
This is the solution I ended up using...
NSDictionary *timelineData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:&jsonError];
if (timelineData) {
tweets = [NSMutableArray new];
for (NSDictionary * obj in timelineData) {
NSString *text = [obj objectForKey:#"text"];
[tweets addObject:text];
}
[self updateTableView];
}
Hopefully this helps a few people in the future.