IOS JSON Parsing Nested Data - ios

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

Related

How To Get Particular Values From JSON and Plot on Map view Using Objective C?

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.

Retrieving keys from NSDictionary

I'm having a hard time managing to pull anything out of a JSON response when querying TMDb. Despite spending most of the weekend searching these forums and others, I am no nearer a solution.
In my header file I have:
#property (nonatomic,strong) NSDictionary * fetchedData;
The dictionary is populating correctly, since the first part of the JSON response looks like this when I use:
NSLog(#"fetchedData: %#", fetchedData);
fetchedData: {
page = 1;
results = (
{
adult = 0;
id = 1245;
"known_for" = (
{
adult = 0;
"backdroppath" = "/hbn46fQaRmlpBuUrEiFqv0GDL6Y.jpg";
"genreids" = ( 878, 28, 12 );
id = 24428;
"mediatype" = movie;
"original_language" = en;
"original_title" = "The Avengers";
I've been trying numerous ways to retrieve all instances of "original_title" (or any of the keys) in the response, but I have no hair left to pull out when every attempt is returning NULL, so any suggestions are welcome!
Try this.
NSString *title = fetchedData[#"results"][0][#"known_for"][0][#"original_title"];
Getting data from Response
I think fetchedData is dictionary.So
NSString *strOriginalTitle = [NSString stringWithFormat:#"%#",[[[[[fetchedData valueForKey:#"results"]objectAtIndex:0]valueForKey:#"known_for"]objectAtIndex:0]valueForKey:#"original_title"];
//OR By getting data step by step
NSArray *arrayResults = [fetchedData valueForKey:#"results"];
NSDictionary *dict = [[arrayResults objectAtIndex:0] copy];
NSArray *arrayKnownFor = [dict valueForKey#"known_for"] copy];
NSString *strOriginalTitle = [arrayKnownFor objectAtIndex:0]valueForKey:#"original_title"];
NSLog(#"The original_title is - %#",strOriginalTitle);

Weathermap API not able to parse completely in iOS

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

SLRequest Twitter iOS

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.

using json, read contents in objective c

I'm learning a very basic method to download data from a weather api.
Basically trying to follow a tutorial.
Using the URL, I am able to download the data in JSON format into a dictionary. Then put into an array.
My question now is how do I read the particular value of an item in the array.
For example, when I do an NSLOG of the array I get the following... I only cut/paste a couple as there are 55 items.
So my question is how do I grab a particular value our of this array?
2013-03-18 14:37:57.576 LocalWeatherV3[1220:c07] loans: {
UV = 2;
"dewpoint_c" = "-4";
"dewpoint_f" = 24;
"dewpoint_string" = "24 F (-4 C)";
"display_location" = {
city = "Jersey City";
country = US;
"country_iso3166" = US;
elevation = "47.00000000";
full = "Jersey City, NJ";
latitude = "40.75180435";
longitude = "-74.05393982";
state = NJ;
"state_name" = "New Jersey";
zip = 07097;
};
estimated = {
};
"feelslike_c" = 2;
"feelslike_f" = 35;
"feelslike_string" = "35 F (2 C)";
"forecast_url" = "http://www.wunderground.com/US/NJ/
here is a piece of the .m
- (void)fetchedData:(NSData *)responseData {
//parse out the json data
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
NSArray* latestLoans = [json objectForKey:#"current_observation"]; //2
NSLog(#"loans: %#", latestLoans); //3
// 1) Get the latest loan
//NSDictionary* loan = [latestLoans objectAtIndex:1];
NSInteger counter = [latestLoans count];
thanks in advance!!
so when I do this
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData //1
options:kNilOptions
error:&error];
and i mouse over the local watch, I see
json NSDictionary * 0x08d62d40
[0] key/value pair
key id 0x08d61cf0
value id 0x08d62100
[1] key/value pair
key id 0x08d62150
value id 0x08d633a0
then i do
NSArray* latestLoans = [json objectForKey:#"current_observation"]; //2
NSLog(#"loans: %#", latestLoans); //3
and one of the items I want is in "latestloans" which is where all that data shows up. so I cant figure out how to grab one of the items
Let's assume you're trying to grab the forecast url. It's as simple as:
// update this line
NSDictionary *latestLoans = [json objectForKey:#"current_observation"];
// url variable will contain the first forecast url in the array
NSString *url = [latestLoans objectForKey:#"forecast_url"];

Resources