Weathermap API not able to parse completely in iOS - 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);

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.

IOS JSON Parsing Nested Data

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

Get values out of data from NSJSONSerialization

I have some JSON data which is pulled from a URL. The code I have written works fine to download the JSON and parse it, but I cannot seem to access it how I need too, especially where the data is contained as a sub-element of another one.
Here is the JSON format:
{
address = "<null>";
city = "<null>";
country = UK;
"country_code" = GB;
daylight = 1;
for = daily;
items = (
{
asr = "5:22 pm";
"date_for" = "2013-7-1";
dhuhr = "1:01 pm";
fajr = "2:15 am";
isha = "11:47 pm";
maghrib = "9:24 pm";
shurooq = "4:39 am";
}
);
latitude = "50.9994081";
link = "http://muslimsalat.com/UK";
longitude = "0.5039011";
"map_image" = "http://maps.google.com/maps/api/staticmap?center=50.9994081,0.5039011&sensor=false&zoom=13&size=300x300";
"postal_code" = "<null>";
"prayer_method_name" = "Muslim World League";
"qibla_direction" = "119.26";
query = "51.000000,0.500000";
state = "<null>";
timezone = 0;
title = UK;
"today_weather" = {
pressure = 1020;
temperature = 14;
};
}
(These are Islamic prayer times.)
My Objective-C so far is this:
-(CLLocationCoordinate2D) getLocation{
CLLocationManager *locationManager = [[[CLLocationManager alloc] init] autorelease];
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = kCLDistanceFilterNone;
[locationManager startUpdatingLocation];
CLLocation *location = [locationManager location];
CLLocationCoordinate2D coordinate = [location coordinate];
return coordinate;
}
//class to convert JSON to NSData
- (IBAction)getDataFromJson:(id)sender {
//get the coords:
CLLocationCoordinate2D coordinate = [self getLocation];
NSString *latitude = [NSString stringWithFormat:#"%f", coordinate.latitude];
NSString *longitude = [NSString stringWithFormat:#"%f", coordinate.longitude];
NSLog(#"*dLatitude : %#", latitude);
NSLog(#"*dLongitude : %#",longitude);
//load in the times from the json
NSString *myURLString = [NSString stringWithFormat:#"http://muslimsalat.com/%#,%#/daily/5.json", latitude, longitude];
NSURL *url = [NSURL URLWithString:myURLString];
NSData *jsonData = [NSData dataWithContentsOfURL:url];
if(jsonData != nil)
{
NSError *error = nil;
id result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
NSArray *jsonArray = (NSArray *)result; //convert to an array
if (error == nil)
NSLog(#"%#", result);
NSLog(#"%#", jsonArray);
for (id element in jsonArray) {
NSLog(#"Element: %#", [element description]);
}
}
}
When running this code, the only output I get is a list of element names (address, city, country, so on). items is given, but not its child elements. I understand that this is what I am asking the code for with:
for (id element in jsonArray) {
NSLog(#"Element: %#", [element description]);
}
but I do not know how to move onto the next step.
The only data values which I require are in fact the times themselves (so, items>asr, items>dhuhr, etc).
How can I get these values themselves and then save them as values I can work with?
Thank you!
(...); - is Array
{...}; - is Dictionary
so your "element" is Dictionary
use objectForKey:
example:
for (id element in jsonArray) {
NSLog(#"Element asr: %#", [element objectForKey:#"asr"]); // or element[#"asr"]
}
NSArray *jsonArray = (NSArray *)result; //convert to an array
This doesn't 'convert', it's just you promising the compiler that result is really an NSArray. And in this case it's a lie.
Your code is currently just printing a list of the keys in the dictionary that is returned in the JSON. Try this to get to the list of items (it's an array so you need to deal with there possibly being multiple entries):
NSDictionary *result = [NSJSONSerialization ...
for (NSDictionary *itemDict in result[#"items"]) {
NSLog(#"item: %#", itemDict);
}
Then you can extract the times.
You can extract info by following:
NSError* error = nil;
NSDictionary *userInfo; //your main data
if([NSJSONSerialization class])
userInfo = [NSJSONSerialization JSONObjectWithData:[request responseData] options:kNilOptions error:&error];
//to extract items
NSDictionary *items = [[[userInfo objectForKey:#"items"] JSONValue] objectAtIndex:0];

Accessing the xml values from NSDictionary

I am using this xmlreader. Here is my code
NSDictionary *xmlDict = [XMLReader dictionaryForXMLString:responseString error:&error1];
NSLog(#"XMLData: %#",xmlDict);
I can save and log the data and it looks like this.
response = {
Gpn0 = {
text = 10000;
};
Gsn0 = {
text = 4;
};
btn0 = {
text = up;
};
};
}
But how can I access a single element from this dictionary?
NSDictionary *gpn0 = response[#"Gpn0"];
NSNumber *gpn0_text = gpno[#"text"]; // note this is a numeric value
NSDictionary *btn0 = response[#"btn0"];
NSString *btn0_text = gpno[#"text"]; // note this is a string value
so on and so forth

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