NSDictionary failed to read array in webservice - ios

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

Related

Get values from NSDictionary

Hi I'm new to iOS development. I want to get response and add those values to variable.
I tried it but I'm getting below response. I don't understand why there is slashes in this response.
#"[{\"VisitorID\":\"2864983a-e26b-441a-aedf-84e2a1770b8e\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kanasalingam\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]},{\"VisitorID\":\"133bc108-b3bf-468a-9397-e1b0dba449db\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kumar\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]}]"
I tried this :
- (void) sendOtherActiveChats:(NSDictionary *) chatDetails{
NSLog(#"inside sendOtherActiveChats");
NSLog(#"otherDetails Dictionary : %# ", chatDetails);
NSString *VisitorID = [chatDetails objectForKey:#"VisitorID"];
NSString *ProfileID = [chatDetails objectForKey:#"ProfileID"];
NSString *CompanyID = [chatDetails objectForKey:#"CompanyID"];
NSString *VisitorName = [chatDetails objectForKey:#"VisitorName"];
NSString *OperatorName = [chatDetails objectForKey:#"OperatorName"];
NSString *isocode = [chatDetails objectForKey:#"isocode"];
NSLog(#"------------------------Other Active Chats -----------------------------------");
NSLog(#"VisitorID : %#" , VisitorID);
NSLog(#"ProfileID : %#" , ProfileID);
NSLog(#"CompanyID : %#" , CompanyID);
NSLog(#"VisitorName : %#" , VisitorName);
NSLog(#"OperatorName : %#" , OperatorName);
NSLog(#"countryCode: %#" , isocode);
NSLog(#"------------------------------------------------------------------------------");
}
Can some one help me to get the values out of this string ?
You are getting Array of Dictionary in response, but your response is in string so you convert it to NSArray using NSJSONSerialization like this way for that convert your response string to NSData and after that use that data with JSONObjectWithData: to get array from it.
NSString *jsonString = #"[{\"VisitorID\":\"2864983a-e26b-441a-aedf-84e2a1770b8e\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kanasalingam\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]},{\"VisitorID\":\"133bc108-b3bf-468a-9397-e1b0dba449db\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kumar\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]}]";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *e;
NSMutableArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&e];
Now loop through the array and access the each dictionary from it.
for (NSDictionary *dic in jsonArray) {
NSLog(#"%#",[dic objectForKey:#"VisitorID"]);
... and so on.
}
First you need to parse your string.
NSString *aString = #"[{\"VisitorID\":\"2864983a-e26b-441a-aedf-84e2a1770b8e\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kanasalingam\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]},{\"VisitorID\":\"133bc108-b3bf-468a-9397-e1b0dba449db\",\"ProfileID\":\"69c02265-abca-4716-8a2f-ac5d642f876a\",\"CompanyID\":null,\"VisitorName\":\"kumar\",\"OperatorName\":\"baman\",\"Image\":null,\"isocode\":\"lk\",\"CurrentOperator\":[\"69c02265-abca-4716-8a2f-ac5d642f876a\"]}]";
NSData *data = [aString dataUsingEncoding:NSUTF8StringEncoding];
id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#",[[json objectAtIndex:0] objectForKey:#"VisitorID"]);
So you have JSON string and array of 2 objects. So write following code
This will convert JSON string to Array
NSData *myJSONData = [YOUR_JSON_STRING dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSMutableArray *arrayResponse = [NSJSONSerialization JSONObjectWithData:myJSONData options:NSJSONReadingMutableContainers error:&error];
Now use for loop and print data as
for (int i = 0; i < arrayResponse.count; i++) {
NSDictionary *dictionaryTemp = [arrayResponse objectAtIndex:i];
NSLog(#"VisitorID : %#",[dictionaryTemp valueForKey:#"VisitorID"]);
NSLog(#"ProfileID : %#",[dictionaryTemp valueForKey:#"ProfileID"]);
NSLog(#"CompanyID : %#",[dictionaryTemp valueForKey:#"CompanyID"]);
NSLog(#"VisitorName : %#",[dictionaryTemp valueForKey:#"VisitorName"]);
}
Now there are good chances that you will get NULL for some keys and it can cause in crash. So avoid those crash by using Null validations.

parse JSON weather object from Open Weather Map API using AFNetworking

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;

Parsing of JSON array returning blank array

I have an array which is of below kind.
{"Hotweeks":[{"Image":"http://www.example.com/wp-content/uploads/0970E01L.jpg","Description":"Ocean Shores, WA","PostTitle":"Windjammer Condominiums"},
{"Image":"","Description":"","PostTitle":"0970O01L"},
{"Image":"","Description":"","PostTitle":"0970I08L"},
{"Image":"","Description":"","PostTitle":"0970I06L"},
{"Image":"","Description":"","PostTitle":"0970I04L"},
{"Image":"","Description":"","PostTitle":"0970i03L"},
{"Image":"","Description":"","PostTitle":"0970I02L"},
{"Image":"","Description":"","PostTitle":"0970I01L"},
{"Image":"","Description":"","PostTitle":"0970E02L"},
{"Image":"","Description":"","PostTitle":"0970E01L"},
{"Image":"http://www.example.com/wp-content/uploads/0936E01L.jpg","Description":"Manson, WA","PostTitle":"Wapato Point"},
{"Image":"","Description":"","PostTitle":"0936O05L"},
{"Image":"","Description":"","PostTitle":"0936O04L"},
{"Image":"","Description":"","PostTitle":"0936O03L"},
{"Image":"","Description":"","PostTitle":"0936O02L"},
{"Image":"","Description":"","PostTitle":"0936O01L"},
{"Image":"","Description":"","PostTitle":"0936I01L"},
{"Image":"","Description":"","PostTitle":"0936E03L"},
{"Image":"","Description":"","PostTitle":"0936E02L"},
{"Image":"","Description":"","PostTitle":"0936E01L"}]}
Which I am trying to parse using the below code.
NSArray *array = [NSJSONSerialization JSONObjectWithData:[returnString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];
NSLog(#"Size of array is %ld",[array count]);
NSDictionary *dictionary = [array objectAtIndex:0];
NSString *test = [dictionary objectForKey:#"Image"];
NSLog(#"Value for image is %#",test);
This is returning null in Nslog.
…"Description":"Ocean Shores, WA,"PostTitle":…
is missing a " after Ocean Shores, WA. It should be
…"Description":"Ocean Shores, WA","PostTitle":…
Use a JSON validator to check for this type of thing. There are many to pick from. I use the Chrome apps JSON Lint and JSON Editor.
The top level of your Json file is an object, not an array (it doesn't start with '['). That being said, if you check array's type like this: NSLog("%#", [array class] you'll probably see it's a NSDictionary.
To get the array you can do this:
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:[returnString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];
NSArray *array = jsonDict[#"Hotweeks"];
NSLog(#"Size of array is %ld",[array count]);
NSDictionary *dictionary = [array objectAtIndex:0];
NSString *test = [dictionary objectForKey:#"Image"];
NSLog(#"Value for image is %#",test);

iOS enumerate json remove objectkey

I'm struck how to enumerate JSON by remove first object in iOS programming as below
From
[{"001": {"name":"test", "url":"test"},"002":{"name":"test1", "url":"test1"},"003":{"name":"test2", "url":"test2"}}]
to
[ {"name":"test", "url":"test"},{"name":"test1", "url":"test1"},{"name":"test2", "url":"test2"}]
Pls help to recommend me or suggestion coding.
Thank you.
Try this,
NSArray *jsonArray = //parsedJsonArray
NSDictionary *values = [jsonArray objectAtIndex:0];
NSArray *valuesArray = [values allValues];
And the valuesArray will contain the data in format,
[ {"name":"test", "url":"test"},
{"name":"test1", "url":"test1"}, {"name":"test2", "url":"test2"}]
You can easily convert a json string to a NSMutableArray :
NSError *error;
// Get a NSMutableArray from the json string
NSData *data = [yourJsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableArray *arrayResult = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
// Remove the first object
[arrayResult removeObject:[arrayResult firstObject]];
jsonDataArray1=[[NSMutableArray alloc]initWithArray:[JSON objectForKey:#"001"]];
jsonDataArray2=[[NSMutableArray alloc]initWithArray:[JSON objectForKey:#"002"]];
jsonDataArray3=[[NSMutableArray alloc]initWithArray:[JSON objectForKey:#"003"]];
jsonDataArrayFinal=[[NSMutableArray alloc]initWithObjects:jsonDataArray1,jsonDataArray2,jsonDataArray3 nil];
initialize all above arrays in viedidload

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