parse JSON weather object from Open Weather Map API using AFNetworking - ios

I am using AFNetworking to retrieve information about the weather for a specific location, e.g:
http://api.openweathermap.org/data/2.5/weather?q={New%20York%20City}
I am using the AFNetworking framework but I am having the problems parsing some objects of the JSON.
If I have an NSDictionary with the MAIN object information from the JSON:
NSDictionay *main = [responseObject objectForKey:#"main"];
If I log the main NSDictionary I will get the following valid output:
"main":{
"temp":296.78;
"pressure":1011;
"humidity":69;
"temp_min":293.15;
"temp_max":299.82
};
Although if I create a NSDictionary containing the weather object I will get the following information whenever logging it to the console:
NSDictionay *weather = [responseObject objectForKey:#"weather"];
"weather":(
{
"id":801;
"main":"Clouds";
"description":"few clouds";
"icon":"02d"
}
);
The parsed information contains ( brackets instead of [ from the original response. This does not allow me to correctly access the inside attributes of the weather object.
Summing up, I am able to access all the inside variables of the MAIN object, but I cannot access the attributes of the Weather object (e.g access the icon attribute).
Can someone help me with this ?
Thank you,

You calling your service as below.
NSString *query = #"http://api.openweathermap.org/data/2.5/weather?q={New%20York%20City}";
NSLog(#"%#",query);
query = [query stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *jsonData = [[NSString stringWithContentsOfURL:[NSURL URLWithString:query] encoding:NSUTF8StringEncoding error:nil] dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *results = jsonData ? [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error] : nil;
Now print Response :
NSLog(#"weather==%#",[results objectForKey:#"weather"]);
NSLog(#"description==%#",[[[results objectForKey:#"weather"] objectAtIndex:0] objectForKey:#"description"]);
NSLog(#"icon==%#",[[[results objectForKey:#"weather"] objectAtIndex:0] objectForKey:#"icon"]);
NSLog(#"id==%#",[[[results objectForKey:#"weather"] objectAtIndex:0] objectForKey:#"id"]);
NSLog(#"main==%#",[[[results objectForKey:#"weather"] objectAtIndex:0] objectForKey:#"main"]);
Your Response is :
whwather==(
{
description = "sky is clear";
icon = 01d;
id= 800;
main= Clear;
}
)
description== "sky is clear";
icon == 01d;
id == 800;
main == Clear;

Related

NSDictionary failed to read array in webservice

I'm newbie in developing Xcode 5 and unable to connect to SQLServer via php.
The php result is this:
{"user":[{"user_id":"2393", "id":"740049"}], "succeed":1}
This webservice created not by me but my team. I tried to track the process via NSLog and found the problem is NSDictionary i created unable to read this kind of format.
This is my NSDictionary
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:urlData option:NSJONReadingMutableContainers error:&error];
success=[json[#"success"] integerValue];
NSLog(#"Success:%ld", (long)success);
if my NSDictionary were able to read the data then the success should be 1 but it keep showing 0. I find the problem is that i cant parse that array in dictionary. Could anyone help me fix this thing?
You mistype the key value. it will be #"succeed". But you type #"success"
NSJSONSerialization *jsonData = [NSJSONSerialization JSONObjectWithData: urlData options:NSJSONReadingMutableContainers error:&error];
int success=[[(NSDictionary *)jsonData valueForKey:#"succeed"]integerValue];
NSLog(#"Success:%ld", (long)success);
Typo:
success=[json[#"succeed"] integerValue];
// ^^^^^^^
//returnString is {"user":[{"user_id":"2393", "id":"740049"}], "succeed":1};
NSDictionary *response = [returnString dataUsingEncoding:NSUTF8StringEncoding];
NSArray *users =[NSArray alloc]init];
if([[response valueForKey:#"succeed"] integerValue] == 1)
users = [response valueForKey:#"user"];
for(NSDictionary *user in users)
NSLog(#"User : %#", user);
Sample Output
User: [{user_id:2393,id:740049},{user_id:2394,id:740050}...,{user_id:2395,id:740051}];

reading a json object from a website in objective c

I need to separate sub person, name, age, home addr, office addr from below given json object retrieved from a website
{ "person" :
[{"subperson":{"home":{"id":"kljljk"},"name":"person3","age":"18","addr":{"home addr":"ksdjr","office addr":"kjshdg"}}}]}
tried nsjsonserialization,sbjson and touchJSON api's. returns a dictionary in which person is the key and everything else is the value(format of json string specified below the code)
my code:
NSURLRequest *urlreq = [NSURLRequest requestWithURL:url];
NSData *response = [NSURLConnection sendSynchronousRequest:urlreq returningResponse:nil error:nil];
[webviv loadRequest:urlreq];
SBJsonParser *jsonparser = [SBJsonParser new];
NSDictionary *json = [jsonparser objectWithData:response];
NSLog(#"%#\n", json);
for(id key in json)
{
NSLog(#"%#=%#",key,[json objectWithKey: key]);
}
//output is
person = (everythingelse starting with [, can't separate name and other required things)
//using NSJSONSerialization
if ([NSJSONSerialization JSONObjectWithData:response options:0 error:&error])
{
NSLog(#"json");
}
NSData *pTL = [NSJSONSerialization JSONObjectWithData:response options:0 error:&error];
NSLog(#"%#",pTL);
//Output is the same
//for(int i=0;i<[pTL count];i++)
//{
//NSLog(#"%d",i);
//}
//even with for loop the output is the same
Tell your backend guys(the person who wrote this web service) to change "[" as "(" and "]" as")". ( is array { is dictionary. [ is nothing for us we can differentiate it
There is a problem with your JSON structure.
For instance, the following is not a legal JSON string:
"subperson":"home":{"id":"kljljk"}
Try replacing it with the following:
{"person":[{"subperson":{"id":"kljljk","name":"person3","age":"18","addr":{"homeaddr":"ksdjr","office addr":"kjshdg"}}}]}
You can use any kind of online JSON parser tool to verify the JSON structure before continuing to debug your code.
Also you should read a little about JSON syntax here.

Write JSON from textfields to a file for iOS 5+

I'm new to iOS programming, and having trouble finding a beginner-level explanation of how to write the contents of multiple text fields to a local json file in such a way to keep everything organized.
For example, a user form would have Name, Address, Email, etc., which would need to be put into a Customer object.
The purpose of this is to save data from several forms, and eventually pass that data to a database.
You'll need to convert your text fields into a dictionary (or dictionary of dictionaries). Once you have that done, you convert the dictionary into JSON data and save that:
NSError *error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myJSONDict options:0 error:&error];
if (jsonData != nil) {
NSString *jsonFilePath = ...;
BOOL status = [jsonData writeToFile:jsonFilePath atomically:YES];
if (!status) {
NSLog(#"Oh no!");
}
} else {
NSLog(#"My JSON wasn't valid: %#", error);
}
You just need to create the path and check the status.
NSMutableDictionary* dict = [NSMutableDictionary dictionary];
[dict setObject:form.name.text forKey:#"name"]'
[dict setObject:form.address.text forKey:#"address"];
...
NSString* jsonString = [yourFavoriteJsonTool convertToJson:dict];

SBJson displays null

I am trying to parse some json data with SBJson to show the current temperature. The example code from this tutorial works perfect: Tutorial: Fetch and parse JSON
When I change the code to my json feed i get a null. I am kind of new to JSON but followed every tutorial and documentation I found. The json source i used: JSON Source
My code with sbjson:
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
self.responseData = nil;
NSArray* currentw = [(NSDictionary*)[responseString JSONValue] objectForKey:#"current_weather"];
//choose a random loan
NSDictionary* weathernow = [currentw objectAtIndex:0];
//fetch the data
NSNumber* tempc = [weathernow objectForKey:#"temp_C"];
NSNumber* weatherCode = [weathernow objectForKey:#"weatherCode"];
NSLog(#"%# %#", tempc, weatherCode);
and of course I have already implemented the other sbjson code.
There is no current_weather key in the JSON data you posted. The structure is:
{ "data": { "current_condition": [ { ..., "temp_C": "7", ... } ], ... } }
Here's a visual representation:
Therefore, to get to temp_C, you'd need to first obtain the top-level data property:
NSDictionary* json = (NSDictionary*)[responseString JSONValue];
NSDictionary* data = [json objectForKey:#"data"];
then, from that, obtain the current_location property:
NSArray* current_condition = [data objectForKey:#"current_condition"];
and finally, from the current_location array, get the element you're interested in:
NSDictionary* weathernow = [current_condition objectAtIndex:0];
Also note that temp_C and weatherCode are strings, not numbers. To transform them to numbers, instead of:
NSNumber* tempc = [weathernow objectForKey:#"temp_C"];
NSNumber* weatherCode = [weathernow objectForKey:#"weatherCode"];
you could use something like:
int tempc = [[weathernow objectForKey:#"temp_C"] intValue];
int weatherCode = [[weathernow objectForKey:#"weatherCode"] intValue];
(or floatValue / doubleValue if the value is not supposed to be an int, but rather a float or a double)
You would then use %d (or %f for float / double) as a format string:
NSLog(#"%d %d", tempc, weatherCode);
Provided link returns json without current_weather parameter. There is only current_condition parameter, please review this.
Use NSJSONSerialization instead of JSONValue.
NSData* data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* jsonDict = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
NSLog(#"jsonDict:%#",jsonDict);
In your link, there is no current_weather key.
NSString* tempc = [[[[jsonDict objectForKey:#"data"] objectForKey:#"current_condition"] objectAtIndex:0] objectForKey:#"temp_C"];

Understand and use this JSON data in iOS

I created a web service which returns JSON or so I think. The data returned look like this:
{"invoice":{"id":44,"number":42,"amount":1139.99,"checkoutStarted":true,"checkoutCompleted":true}}
To me, that looks like valid JSON.
Using native JSON serializer in iOS5, I take the data and capture it as a NSDictionary.
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:[request responseData] options:kNilOptions error:&error];
NSLog(#"json count: %i, key: %#, value: %#", [json count], [json allKeys], [json allValues]);
The output of the log is:
json count: 1, key: (
invoice
), value: (
{
amount = "1139.99";
checkoutCompleted = 1;
checkoutStarted = 1;
id = 44;
number = 42;
}
)
So, it looks to me that the JSON data has a NSString key "invoice" and its value is NSArray ({amount = ..., check...})
So, I convert the values to NSArray:
NSArray *latestInvoice = [json objectForKey:#"invoice"];
But, when stepping through, it says that latestInvoice is not a CFArray. if I print out the values inside the array:
for (id data in latestInvoice) {
NSLog(#"data is %#", data);
}
The result is:
data is id
data is checkoutStarted
data is ..
I don't understand why it only return the "id" instead of "id = 44". If I set the JSON data to NSDictionary, I know the key is NSString but what is the value? Is it NSArray or something else?
This is the tutorial that I read:
http://www.raywenderlich.com/5492/working-with-json-in-ios-5
Edit: From the answer, it seems like the "value" of the NSDictionary *json is another NSDictionary. I assume it was NSArray or NSString which is wrong. In other words, [K,V] for NSDictionary *json = [#"invoice", NSDictionary]
The problem is this:
NSArray *latestInvoice = [json objectForKey:#"invoice"];
In actual fact, it should be:
NSDictionary *latestInvoice = [json objectForKey:#"invoice"];
...because what you have is a dictionary, not an array.
Wow, native JSON parser, didn't even notice it was introduced.
NSArray *latestInvoice = [json objectForKey:#"invoice"];
This is actually a NSDictionary, not a NSArray. Arrays wont have keys. You seem capable from here.
Here I think You have to take to nsdictionary like this
NSData* data = [NSData dataWithContentsOfURL: jsonURL];
NSDictionary *office = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSDictionary *invoice = [office objectForKey:#"invoice"];

Resources