How To Get Particular Values From Json Response Using Objective C? - ios

I am trying to get response of first key value without mentioning key name of "A" using objective C. I cant get exactly, please help me to get from below response.
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers error:&error];
NSDictionary *response = [JSON[#"response"]firstObject];
response = {
A = {
company = (
{
no = "115";
student = "Mich";
school = (
{
grade = A;
}
);
test = "<null>";
office = tx;
}
);
};
}

There are a few ways to do this, depending on your exact requirements. If you just need to access the value of each key in JSON[#"response"], you can enumerate the JSON dictionary:
[JSON enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSDictionary *dict = (NSDictionary *)obj;
...
if (shouldStop) { // whatever condition you want, if any
*stop = YES;
}
}];
If you want some kind of ordering, you need to use [JSON allKeys]:
NSArray *keys = [[JSON allKeys] sortedArrayUsing...]; // Use whichever sort method you like
for (NSString *key in keys) {
NSDictionary *dict = JSON[key];
...
}
If all you want are the values, you can use [JSON allValues]. Sort if desired.

Related

New to JSON API how to access the values in objective-c?

Below is my code to access the JSON API from Edmunds.com, this works perfectly to access the information I am just having trouble with accessing the key, value pairs.
NSURL *equipmentURL = [NSURL URLWithString: [NSString stringWithFormat:#"https://api.edmunds.com/api/vehicle/v2/styles/%#/equipment?fmt=json&api_key=%#", self.carID, apiKey]];
NSData *jsonData = [NSData dataWithContentsOfURL:equipmentURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
self.engineArray = [NSMutableArray array];
NSArray *equipmentArray = [dataDictionary objectForKey:#"equipment"];
for (NSDictionary *carInfoDictionary in equipmentArray) {
NSArray *attributes = [carInfoDictionary objectForKey:#"attributes"];
NSLog(#"%#", attributes);
}
In the NSLog from the above code shows this:
2016-11-03 10:21:26.029 CarWise[25766:1896339] (
{
name = "Engine Immobilizer";
value = "engine immobilizer";
},
{
name = "Power Door Locks";
value = "hands-free entry";
},
{
name = "Anti Theft Alarm System";
value = "remote anti-theft alarm system";
}
)
My main question is how can I access the name and value for each array? Let's say I want to create a UILabel that will have the string of one of the values?
Probably this will help
// Array as per the post
NSArray *attributes = (NSArray *)[carInfoDictionary objectForKey:#"attributes"];
// Loop to iterate over the array of objects(Dictionary)
for (int i = 0; i < attributes.count; i++) {
NSDictionary * dataObject = [NSDictionary dictionaryWithDictionary:(NSDictionary *)attributes[i]];
// This is the value for key "Name"
NSString *nameData = [NSString stringWithString:[dataObject valueForKey:#"name"]];
NSLog(#"Value of key : (name) : %#", nameData);
}

Parse from JSON response

I am getting the JSON response
(
{
Response = success;
UserId = 287;
}
)
I tried to parse the user id with below code
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:receivedData options:0 error:&e];
NSLog(#"%#", dataDictionary);
NSString *useridstring=[dataDictionary valueForKey:#"UserId"];
But am getting the user id ( 287 ).
Please suggest me that how to get user id without paraparentheses
Your response is not a dictionary, it's an array. So your code should look like this:
NSArray *dataArray = [NSJSONSerialization JSONObjectWithData:receivedData options:0 error:&e];
NSLog(#"%#", dataArray);
NSDictionary *dataDictionary = dataArray[0]; //Same as objectAtIndex:
NSString *userIDString = dataDictionary[#"UserID"]; //Same as objectForKey:
//If you're still getting parens try this:
//int userIDInt = [dataDictionary[#"UserID"] intValue];
You need to fetch integer value from your JSON response.
int userid = [[dataDictionary valueForKey:#"UserId"] intValue];
If getting parentheses in integer response too, then it is problem with JSON response recived. for a workaround you can use -
NSString *useridstring=[dataDictionary valueForKey:#"UserId"];
int userid = [[useridstring substringWithRange:NSMakeRange(1, useridstring.length - 2)] intValue]
EDIT --
You are getting an array in response, for this you have to use -
int userid = [[dataDictionary valueForKey:#"UserId"] firstObject];

Json Response parsing

I got json reponse in the following way...i have tried to parse in many ways all went ruin.
dic:
(
{
events = {
id = 1;
name = "Event One";
};
},
{
events = {
id = 2;
name = "Test 2";
};
},
{
events = {
id = 12;
name = "vivek 11";
};
},
)
NSDictionary *jsonDictionaryResponse = [response JSONValue];
NSString *name=[[[jsonDictionaryResponse objectForKey:#"events"]objectAtIndex:0]valueForKey:#"name"];
json response:
Login response :[{"events":{"id":"1","name":" Event
One"}},{"events":{"id":"2","name":"Test
2"}},{"events":{"id":"12","name":"vivek
11"}},{"events":{"id":"13","name":"Baby's Day
out"}},{"events":{"id":"15","name":"Childrens
Day"}},{"events":{"id":"16","name":"event
two"}},{"events":{"id":"17","name":"Test
Creattion"}},{"events":{"id":"29","name":"Susan
Test"}},{"events":{"id":"30","name":"Summer
Holidays"}},{"events":{"id":"38","name":"Event
7"}},{"events":{"id":"69","name":"vivek event for
tests"}},{"events":{"id":"102","name":"chinees food mela"}}]
first transform your response string to NSData. then try this:
NSError *error;
NSArray *jSONArray = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
for (NSDictionary *dict in jSONArray) {
NSDictionary *event = [dict objectForKey=#"events"];
NSString *name = [event objectForKey:#"name"];
....
}
The easiest way to understand a JSON object in Objective-C is to understand how it breaks things up into Arrays and Dictionaries. Every time you see a "[" think Array. Every time you see a "{" think Dictionary.
An Array can have Dictionary or other Array objects as part of the collection and a Dictionary can have Array or more Dictionary objects which can contain more Arrays or Dictionaries.
If you remember that "[ ]" means Array and "{ }" means Dictionary, you will know JSON in Objective-C.
Check that result coming as JSON. it is not aDictionary check it
here
PLease find the code here
NSArray *jsonArrayResponse = [response JSONValue];
NSDictionary *firstDic = [jsonArrayResponse objectAtIndex:0];
NSDictionary *secondDic = [firstDic objectForKey:#"events"];
NSLog(#"The values in the events dictioanry is %# ",[secondDic allValues]);
NSString *stringNAme = [secondDic objectForKey:#"id"];

Cant access serialized JSON data (NSJSONSerialization)

I get this JSON from a web service:
{
"Respons": [{
"status": "101",
"uid": "0"
}]
}
I have tried to access the data with the following:
NSError* error;
//Response is a NSArray declared in header file.
self.response = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSString *test = [[self.response objectAtIndex:0] objectForKey:#"status"]; //[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance
NSString *test = [[self.response objectForKey:#"status"] objectAtIndex:0]; //(null)
But none of them work, if i NSLog the NSArray holding the serialized data, this i what i get:
{
Respons = (
{
status = 105;
uid = 0;
}
);
}
How do i access the data?
Your JSON represents a dictionary, for whom the value associated with the Respons key is an array. And that array has a single object, itself a dictionary. And that dictionary has two keys, status and uid.
So, for example, if you wanted to extract the status, I believe you need:
NSArray *array = [self.response objectForKey:#"Respons"];
NSDictionary *dictionary = [array objectAtIndex:0];
NSString *status = [dictionary objectForKey:#"status"];
Or, in latest versions of the compiler:
NSArray *array = self.response[#"Respons"];
NSDictionary *dictionary = array[0];
NSString *status = dictionary[#"status"];
Or, more concisely:
NSString *status = self.response[#"Respons"][0][#"status"];
Your top level object isn't an array, it's a dictionary. You can easily bypass this and add the contents of that key to your array.
self.response = [[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error] objectForKey:#"Respons"];

How should I read the data from a json string? iphone

I have in a NSString "[{"van" : 1,312, "vuan":12,123}] and in order to get this values for every key, I am doing this:
NSData *data1 = [jsonResponse1 dataUsingEncoding:NSUTF8StringEncoding];
jsonArray = [NSJSONSerialization JSONObjectWithData:data1 options:kNilOptions error:&err];
self.van = [NSMutableArray arrayWithCapacity:1];
self.vuan = [NSMutableArray arrayWithCapacity:1];
for (NSDictionary *json in jsonArray) {
NSString * value = [json objectForKey:#"van"];
[self.van addObject:value];
lbl1.text = value;
NSString * value1 = [json objectForKey:#"vuan"];
[self.vuan addObject:value1];
lbl4.text = value1;
}
May be I don't have to use an array and instead to convert the NSData directly in a NSDictionary.
Anyway, I don't understand why jsonArray is nil, although jsonResponse1 contains the values I have written above.
EDIT: My boss have written the json string wrong. Thank you all for your suggestions!:)
Your JSON is invalid. Fix it. This site is your friend.
http://jsonlint.com/
You need to code more defensively and you need to report errors as they are found.
Firstly check if the JSON parsing failed and if so report the error:
NSData *data1 = [jsonResponse1 dataUsingEncoding:NSUTF8StringEncoding];
jsonArray = [NSJSONSerialization JSONObjectWithData:data1 options:kNilOptions error:&err];
if (jsonArray == nil)
{
NSLog(#"Failed to parse JSON: %#", [err localizedDescription]);
return;
}
Secondly if those keys are not in the JSON, objectForKey: will return nil and when you attempt to add that to the arrays, it will throw an exception, which is something you want to avoid:
for (NSDictionary *json in jsonArray) {
NSString * value = [json objectForKey:#"van"];
if (value != nil)
{
[self.van addObject:value];
lbl1.text = value;
}
else
{
NSLog(#"No 'van' key in JSON");
}
NSString * value1 = [json objectForKey:#"vuan"];
if (value1 != nil)
{
[self.vuan addObject:value1];
lbl4.text = value1;
}
else
{
NSLog(#"No 'vuan' key in JSON");
}
}
So in summary: runtime errors will occur so you need to ensure you handle them. When they occur you need to report them with as much information possible so that you can diagnose and fix them.

Resources