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

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

Related

How to retrieve specific value of key in json?

this is my json content.
[
{
"sha":"30eae8a47d0203ac81699d8fc2ab2632de2d0bba",
"commit":{
"author":{
"name":"Madhura Bhave",
"email":"mbhave#pivotal.io",
"date":"2017-03-23T23:14:32Z"
},
"committer":{
"name":"Madhura Bhave",
"email":"mbhave#pivotal.io",
"date":"2017-03-23T23:14:32Z"
},
"message":"Merge branch '1.5.x'",
}
}
]
and this is my main.i just want to retrieve key value from message and name,email,date from committer dictionary.i got stuck how to do that.
NSMutableArray *CommitArray = [[NSMutableArray alloc] init];
for (NSDictionary *CommitDictionary in CommitJson) {
CommitDict *commitDictObj = [[CommitDict alloc] init];
commitDictObj.message = [CommitDictionary objectForKey:#"message"];
for (NSDictionary *CommitterDictionary in [CommitDictionary objectForKey:#"committer"]) {
Committer *author = [[Committer alloc] init];
author.name = [CommitterDictionary objectForKey:#"name"];
author.email = [CommitterDictionary objectForKey:#"email"];
author.date = [CommitterDictionary objectForKey:#"date"];
}
[CommitArray addObject:commitDictObj];
}
for (int i =0 ; i < [CommitArray count] ; i++){
CommitDict *commitDictObj = [CommitArray objectAtIndex:i];
NSLog(#"Commit Message: %#", commitDictObj.message);
}
return 0;
}
}
i try fetch the json and display it value of message,name,email and date.how can i log the value of message, name, email and date?
Your array contains a dictionary, and that dictionary contains the commit dictionary, not the commit dictionary directly. Replace that part of your code:
for (NSDictionary *CommitDictionary in CommitJson) {
CommitDict *commitDictObj = [[CommitDict alloc] init];
With that:
for (NSDictionary *shaCommitDictionary in CommitJson) {
CommitDict *commitDictObj = [[CommitDict alloc] init];
NSDictionary *CommitDictionary = [shaCommitDictionary objectForKey:#"commit"];
(1) Convert JSON to NSDictionary
NSData *jsonData= ... // Assume you got the data already loaded
NSError *error = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
(2) Access the dictionary values (fast enumeration available by now!!
NSString *message = dictionary[#"message"];
NSDictionary *author = dictionary[#"author"];
NSString *name = author[#"author"];
NSString *email = author[#"author"];
NSString *date = author[#"author"];
// OR:
// NSString *name = dictionary[#"author"][#"author"];
// NSString *email = dictionary[#"author"][#"author"];
// NSString *date = dictionary[#"author"][#"author"];
And thats it. I think the tricky thing is to get the JSON Data to the NSDictionary?
See here: https://stackoverflow.com/a/30561781/464016

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

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.

NSDictionary format

Can anybody help me create an NSDictionary format of the following structure:
{
key1 = "value1";
key2 = "value2";
key3 = [
{
key01 = "value01";
key02 = "value02";
},
{
key01 = "value01";
key02 = "value02";
},
{
key01 = "value01";
key02 = "value02";
}
];
}
Try this code it might help you.
NSDictionary *dicationary = #{
#"key1":#"value1",
#"key2":#"value2",
#"key3":#[#{#"key01":#"value01",#"key02":#"value02"},
#{#"key01":#"value01",#"key02":#"value02"},
#{#"key01":#"value01",#"key02":#"value02"}]
};
There is API in obj-c to convert Json to nsdictionary .I guess you should try that :
First convert json to nsdata (assuming you above JSON is in string format)
2.Then you API to convert that to NSDictionary :
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
Just to answer your question about converting that JSON data to NSDictionary, here it is:
(assuming you already got your JSON data)
// add the first 2 VALUES with it's KEYS
NSMutableDictionary *mainDict = [NSMutableDictionary dictionary];
[mainDict setValue:VALUE1 forKey:KEY1];
[mainDict setValue:VALUE2 forKey:KEY2];
// then for the last KEY, create a mutable array where you will store your sub dictionaries
NSMutableArray *ma = [NSMutableArray array];
NSMutableDictionary *subDict = [NSMutableDictionary dictionary];
[subDict setValue:SUB_VALUE1 forKey:SUB_KEY1];
[subDict setValue:SUB_VALUE1 forKey:SUB_KEY2];
[ma addObject:subDict];
// then add that array to your main dictionary
[mainDict setValue:ma forKey:KEY3];
// check the output
NSLog(#"mainDict : %#", mainDict);
// SAMPLE DATA - Test this if this is what you want
NSMutableDictionary *mainDict = [NSMutableDictionary dictionary];
[mainDict setValue:#"value1" forKey:#"key1"];
[mainDict setValue:#"value2" forKey:#"key2"];
NSMutableArray *ma = [NSMutableArray array];
NSMutableDictionary *subDict = [NSMutableDictionary dictionary];
[subDict setValue:#"subValue1" forKey:#"subKey1"];
[subDict setValue:#"subValue2" forKey:#"subKey2"];
[ma addObject:subDict];
[mainDict setValue:ma forKey:#"key3"];
NSLog(#"mainDict : %#", mainDict);
The following should work for you:
NSString *jsonString = #"{\"ID\":{\"Content\":268,\"type\":\"text\"}}";
NSData *data = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#", jsonDict[#"ID"][#"Content"]);
Will return you:
268

Parse array of dictionaries of json in ios

i wanted to parse this json using this way
{"img":[{"id":"44","name":"\u0625\u0628\u0631\u0627\u0647\u064a\u0645 \u0627\u0644\u0639\u0631\u064a\u0641\u064a","type":"\u0627\u0646\u0627 \u0627\u062a\u0639\u0644\u0645","img":"27039_01355548242.png","school":"\u0625\u0628\u0631\u0627\u0647\u064a\u0645 \u0627\u0644\u0639\u0631\u064a\u0641\u064a","isshow":"1","tarteb":"0","date":"29\/1\/2015 01:15","mob":"16544541321"}]}
i wrote this code to parse it
NSArray * array = [[NSArray alloc]init];
array = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
NSDictionary * dic =array[indexPath.row]; //here is error
NSLog(#"%#",dic);
NSDictionary * info = dic[#"img"];
cell.name.text = info[#"name"];
cell.date.text =info[#"date"];
cell.schoolName.text= info[#"school"];
cell.mobile.text= info[#"mob"];
then i got this error
[__NSCFDictionary objectAtIndex :]: unrecognized selector sent to instance 0x7c986db0
NSDictionary *jsonDictionary = [[NSDictionary alloc] init];
jsonDictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
NSArray *imageArray = jsonDictionary[#"img"];
NSDictionary *firstObject = imageArray[0];
cell.name.text = firstObject[#"name"];
cell.date.text =firstObject[#"date"];
cell.schoolName.text= firstObject[#"school"];
cell.mobile.text= firstObject[#"mob"];
and If there are multiple rows in json,Like:
{"img":[{"id":"44","name":"\u0625\u0628\u0631\u0627\u0647\u064a\u0645 \u0627\u0644\u0639\u0631\u064a\u0641\u064a","type":"\u0627\u0646\u0627 \u0627\u062a\u0639\u0644\u0645","img":"27039_01355548242.png","school":"\u0625\u0628\u0631\u0627\u0647\u064a\u0645 \u0627\u0644\u0639\u0631\u064a\u0641\u064a","isshow":"1","tarteb":"0","date":"29\/1\/2015 01:15","mob":"16544541321"},{"id":"45","name":"\u0625\u0628\u0631\u0627\u0647\u064a\u0645 \u0627\u0644\u0639\u0631\u064a\u0641\u064a","type":"\u0627\u0646\u0627 \u0627\u062a\u0639\u0644\u0645","img":"27039_01355548242.png","school":"\u0625\u0628\u0631\u0627\u0647\u064a\u0645 \u0627\u0644\u0639\u0631\u064a\u0641\u064a","isshow":"1","tarteb":"0","date":"29\/1\/2015 01:15","mob":"16544541321"},{"id":"46","name":"\u0625\u0628\u0631\u0627\u0647\u064a\u0645 \u0627\u0644\u0639\u0631\u064a\u0641\u064a","type":"\u0627\u0646\u0627 \u0627\u062a\u0639\u0644\u0645","img":"27039_01355548242.png","school":"\u0625\u0628\u0631\u0627\u0647\u064a\u0645 \u0627\u0644\u0639\u0631\u064a\u0641\u064a","isshow":"1","tarteb":"0","date":"29\/1\/2015 01:15","mob":"16544541321"}]}
then use this approach, if you need to show id:44 in zeroth row,id:45 in first row,id:46 in second row,...Of table view.
//In View Did Load
NSMutableArray *tableDataSource = [NSMutableArray new];
for (int i = 0; i < imageArray.count; i++)
{
NSDictionary *rowDataDictionary = imageArray[i];
[tableDataSource addObject:rowDataDictionary];
}
//In Cell For Row
NSDictionary *rowData = tableDataSource[indexPath.row];
cell.name.text = rowData[#"name"];
cell.date.text =rowData[#"date"];
cell.schoolName.text= rowData[#"school"];
cell.mobile.text= rowData[#"mob"];
JsonObjectWithData Returns Dictionary, and you should parse the data according to structure of JSON.
Hope this Helps,
As it shown above, JsonObjectWithData returns NSDictionary object, and you should use valueForKey method for taking value which you need.
NSDictionary *jsonDictionary = [[NSDictionary alloc] init];
jsonDictionary = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
NSMutableArray *valueForImgLabel = [jsonDictionary valueForKey:#"img"];
If you have too much value for one element in your JSON Response object, like this ;
{
Name = "Mr. Hope";
Gender = "Male";
Age = 29;
ImageList = (
{
Name = "Front side";
Image = "11111.JPG";
Order = 1;
Date = "07/07/2014";
},
{
Name = "Left Side";
Image = "22222.JPG";
Order = 1;
Date = "10/28/2015";
});
}
You can take all ImageList elements,convertibly, using valueForkey like this;
NSMutableArray *imageListInJSONFile = [jsonDictionary valueForKey:#"ImageList"][0];

After convert JSON array to NSDictionary, what should I do?

I need to parse a JSON array in the following format:
[
{
name: "10-701 machine learning",
_id: "52537480b97d2d9117000001",
__v: 0,
ctime: "2013-10-08T02:57:04.977Z"
},
{
name: "15-213 computer systems",
_id: "525616b7807f01fa17000001",
__v: 0,
ctime: "2013-10-10T02:53:43.776Z"
}
]
So after getting the NSData, I transfer it to a NSDictionary:
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"%#", dict);
But viewing from the console, I think the dictionary is actually like this:
(
{
"__v" = 0;
"_id" = 52537480b97d2d9117000001;
ctime = "2013-10-08T02:57:04.977Z";
name = "10-701 machine learning";
},
{
"__v" = 0;
"_id" = 525616b7807f01fa17000001;
ctime = "2013-10-10T02:53:43.776Z";
name = "15-213 computer systems";
}
)
What do those parenthesis in the outside mean? How should I further transfer this NSDictionary to an NSArray or an NSMutableArray of some Course objects (what I defined myself, try to represent each element of the JSON array)?
Use this code,
NSArray *array = [NSJSONSerialization JSONObjectWithData: responseData options:NSJSONReadingMutableContainers error:&error];
NSDictionary *dict = [array objectAtIndex:0];
Then you can retrieve the values by following code,
NSString *v = [dict objectForKey:#"__v"];
NSString *id = [dict objectForKey:#"_id"];
NSString *ctime = [dict objectForKey:#"ctime"];
NSString *name = [dict objectForKey:#"name"];
The parenthesis are just the result of NSDictionary output format not being exactly the same thing as how JSON is formatted. Your code still successfully converted the JSON into a NSDictionary object.
I think what you really want, though, is an array of dictionaries. Something like this:
NSArray *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSDictionary *firstObject = [json objectAtIndex:0];
After this, firstObject would contain:
{
"__v" = 0;
"_id" = 52537480b97d2d9117000001;
"ctime" = "2013-10-08T02:57:04.977Z";
"name" = "10-701 machine learning";
}
And you can retrieve the information with objectForKey:
NSString *time = [firstObject objectForKey:#"ctime"];
// time = "2013-10-08T02:57:04.977Z"
Hope that helps.

Resources