I am trying to get some keys and values from below nested JSON response. Below I have mentioned my JSON response structure, I need to get the all keys(Red, Green) and key values(Color and ID) from the below response and load into the Array for tableview cell value.
FYI: I have tried by using NSDictionary but I am getting all the time unordered values. I need to get ordered values also. Please help me!
{
response: {
RED: {
Color: "red",
color_id: "01",
},
GREEN: {
Color: "green",
color_id: "02",
}
},
Colorcode: { },
totalcolor: "122"
}
My Code:
NSError *error;
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *responsData = [jsonDictionary objectForKey:#"response"];
NSLog("%#",[responsData objectAtIndex:0]); // here I am getting bad exception
NSDictionary *d1 = responsData.firstObject;
NSEnumerator *enum1 = d1.keyEnumerator;
NSArray *firstObject = [enum1 allObjects];
I have create JSON data through coding so don't consider it just check the following answer
/// Create dictionary from following code
/// it just for input as like your code
NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
NSMutableDictionary * innr = [[NSMutableDictionary alloc] init];
[innr setObject:#"red" forKey:#"Color"];
[innr setObject:#"01" forKey:#"color_id"];
NSMutableDictionary * outer = [[NSMutableDictionary alloc] init];
[outer setObject:innr forKey:#"RED"];
innr = [[NSMutableDictionary alloc] init];
[innr setObject:#"green" forKey:#"Color"];
[innr setObject:#"02" forKey:#"color_id"];
[outer setObject:innr forKey:#"GREEN"];
[dict setObject:outer forKey:#"response"];
// ANS ------ as follow
// get keys from response dictionary
NSMutableArray * key = [[NSMutableArray alloc] initWithArray:[dict[#"response"] allKeys]];
// sort as asending order
NSSortDescriptor* sortOrder = [NSSortDescriptor sortDescriptorWithKey: #"self" ascending: YES];
key = (NSMutableArray *)[key sortedArrayUsingDescriptors: [NSArray arrayWithObject: sortOrder]];
// access inner data from dictonary
for (NSString * obj in key) {
NSLog(#"%#",dict[#"response"][obj][#"Color"]);
NSLog(#"%#",dict[#"response"][obj][#"color_id"]);
}
I think you want same and it will help you!
If you're stuck with this JSON, if you want an array of the values, you can do the following:
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSDictionary *response = json[#"response"];
NSArray *colors = [response allValues];
If you need that array of colors sorted by color_id, for example, you can sort that yourself:
NSArray *sortedColors = [colors sortedArrayUsingDescriptors:#[[[NSSortDescriptor alloc] initWithKey:#"color_id" ascending:TRUE]]];
Related
Response:
{"rsBody":
[{"productId":11,
"productImageUrl":"http:xxxx"},
{"productId":9,
"productImageUrl":"http:"xxxx"}]}
I know this is a repeated question, but still asking cause not getting the right way to do it. I am getting some response from php server as JSON in an array which consists two objects. I want to map the element of both objects productImageUrl in an NSArray. Resultant array should be somewhat like
NSArray =[{#"url":"productImageUrl1"},{#"url":#"ProductImageUrl2"}, nil];
productImageUrl1 = element of 1st object, productImageUrl2 = element of 2nd object.
I am parsing the response and able to to extract it from rsBody.
NSDictionary* response=(NSDictionary*)[NSJSONSerialization
JSONObjectWithData:receivedData options:kNilOptions error:&tempError];
NSArray *rsBody = [response objectForKey:#"rsBody"];
Try this:
NSMutableArray *arr = [[NSMutableArray alloc] init];
NSDictionary* response = [NSJSONSerialization JSONObjectWithData:receivedData options:kNilOptions error:&tempError];
NSArray *rsBody = [response objectForKey:#"rsBody"];
for (NSDictionary *dict in rsBody)
{
NSMutableDictionary *dictURL = [[NSMutableDictionary alloc] init];
[dictURL setValue:[dict valueForKey:#"productImageUrl"] forKey:#"url"];
[arr addObject:dictURL];
}
NSLog(#"%#", arr);
I am very new to Objective-C and iOS programming so be gentle :)
I am trying to add an nsmutabledictionary to and nsmutablearray. I am succeeding but not with the results I was hoping for. Here is my code :
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
NSMutableDictionary *messages = [[NSMutableDictionary alloc] init];
NSMutableArray *array = [[NSMutableArray alloc] init];
[dictionary setValue:#"lat1" forKey:#"lat"];
[dictionary setValue:#"long1" forKey:#"long"];
[dictionary setValue:#"alt1" forKey:#"alt"];
[messages setObject:dictionary forKey:#"messages"];
[array addObject:messages];
[dictionary setValue:#"lat2" forKey:#"lat"];
[dictionary setValue:#"long2" forKey:#"long"];
[dictionary setValue:#"alt2" forKey:#"alt"];
[messages setObject:dictionary forKey:#"messages"];
[array addObject:messages];
NSLog(#"%#",array);
NSLog(#"%lu",(unsigned long)[array count]);
Here is the NSLog output:
2014-06-05 10:29:27.377 dicttest[4863:60b] (
{
messages = {
alt = alt2;
lat = lat2;
long = long2;
};
},
{
messages = {
alt = alt2;
lat = lat2;
long = long2;
};
}
)
2014-06-05 10:29:27.386 dicttest[4863:60b] 2
Here is what I was hoping to achieve:
2014-06-05 10:29:27.377 dicttest[4863:60b] (
{
messages = {
alt = alt1;
lat = lat1;
long = long1;
};
},
{
messages = {
alt = alt2;
lat = lat2;
long = long2;
};
}
)
2014-06-05 10:29:27.386 dicttest[4863:60b] 2
If I the dictionary straight to the array (instead of add the dictionary to messages and then adding that to the array) then I get the output I am looking for. Can somebody explain to me exactly what I am doing wrong?
It looks to me like you want:
An array
At index 0:
A dictionary with a single key "messages"
A dictionary with keys "alt", "lat", and "long"
At index 1:
A dictionary with a single key "messages"
A dictionary with keys "alt", "lat", and "long"
The data in the second array entry should use the same keys, but different data. As the others have pointed out, your mistake is using a single dictionary "dictionary"
When you add an object to a collection like a dictionary or array, the collection holds a pointer to the object, not a copy of the object. If you add the same object to a collection more than once, you have 2 pointers to the same object, not 2 unique objects.
When you add your "dictionary" object, to your structure, change it, and add it again, you are not getting the result you expect because both entries in your structure point to a single dictionary. When you change the values, it changes in both places.
The same goes for your "messages" dictionary. You need 2 of those as well.
Fix your code by adding new dictionaries, dictionary2 and messages2:
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
NSMutableDictionary *dictionary2 = [[NSMutableDictionary alloc] init];
NSMutableDictionary *messages = [[NSMutableDictionary alloc] init];
NSMutableDictionary *messages2 = [[NSMutableDictionary alloc] init];
NSMutableArray *array = [[NSMutableArray alloc] init];
[dictionary setValue:#"lat1" forKey:#"lat"];
[dictionary setValue:#"long1" forKey:#"long"];
[dictionary setValue:#"alt1" forKey:#"alt"];
[messages setObject:dictionary forKey:#"messages"];
[array addObject:messages];
[dictionary2 setValue:#"lat2" forKey:#"lat"];
[dictionary2 setValue:#"long2" forKey:#"long"];
[dictionary2 setValue:#"alt2" forKey:#"alt"];
[messages2 setObject: dictionary2 forKey:#"messages"];
[array addObject: messages2];
NSLog(#"%#",array);
NSLog(#"%lu",(unsigned long)[array count]);
You might also look at using object literal syntax, e.g.:
dictionary[#"lat"] = #"lat1";
dictionary[#"long"] = #"long1";
dictionary[#"alt"] = #"alt1";
messages[#"messages"] = dictionary;
If you didn't need the whole thing to be mutable, you could even do everything with one line:
NSMutableArray *array = [
#[
#{#"messages": #{#"lat": #"lat1", #"long": #"long1", #"alt": #"alt1"}},
#{#"messages": #{#"lat": #"lat2", #"long": #"long2", #"alt": #"alt2"}}
];
Or to make it mutable:
NSMutableArray *array = [
#[
[#{#"messages":
[#{#"lat": #"lat1", #"long": #"long1", #"alt": #"alt1"} mutableCopy]} mutableCopy],
[#{#"messages":
[#{#"lat": #"lat2", #"long": #"long2", #"alt": #"alt2"} mutableCopy]} mutableCopy]
] mutableCopy];
EDIT: to add contents dynamically, you could use a method like this: (assuming that array is an instance variable)
- (void) addMessageWithLat: (NSString *) latString
long: (NSString *) longString
alt: (NSString *) altString;
{
NSMutableDictionary *messages = [[NSMutableDictionary alloc] init];
NSDictonary *contents =
[#{#"lat": latString,
#"long": longString,
#"alt": altString}
mutableCopy];
messages[#"messages"] = contents;
[array addObject: messages];
}
The problem is that you are making adding the new values in the same object reference. So the new Value will replace the older one. Just add this line before [dictionary setValue:#"lat2" forKey:#"lat"];
dictionary = [NSMutableDictionary alloc]init];
and this line before the second instance of [messages setObject:dictionary forKey:#"messages"];
messages = [[NSMutableDictionary alloc] init];
I have a NSArray that looks like this:
{"result":
[
{
"epoch":"1371333600"
},
{
"epoch":"1371420000"
},
{
"epoch":"1371333600"
}
]
}
I want to sort the NSArray and make a new one so i can use it easier with the tableview methods to count the sections and rows.
All the dates that are the same need to be in one section.
The array should look like the example below but i don’t know how to get there. I have tried NSPredicate and used a loop but it won’t work.
What i want:
{"result":
[
{"data":
[
{
"epoch":"1371333600"
},
{
"epoch":"1371333600"
}
]
},
{"data":
[
{
"epoch":"1371420000"
}
]
}
]
}
My NSPredicate looks like this, but does not give me the result.
_finalArray = [[NSMutableArray alloc] init];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"epoch IN %#", [_resultArray valueForKey:#"epoch"]];
_predicateDate = [NSMutableArray arrayWithArray:[dataSortArray filteredArrayUsingPredicate:predicate]];
if ([_predicateDate count] != 0)
{
NSDictionary *itemsArrayDict = [NSDictionary dictionaryWithObject:_predicateDate forKey:#"data"];
[_finalArray addObject:itemsArrayDict];
}
NSOrderedSet is awesome for this occasion as it allows you to get the unique strings.
NSDictionary *dict1 = [NSDictionary dictionaryWithObject:#"2222222" forKey:#"epoch"];
NSDictionary *dict2 = [NSDictionary dictionaryWithObject:#"2222222" forKey:#"epoch"];
NSDictionary *dict3 = [NSDictionary dictionaryWithObject:#"1111111" forKey:#"epoch"];
NSArray *dictArray = #[dict1, dict2, dict3];
NSMutableArray *finalArray = [[NSMutableArray alloc]init];
NSArray *epoches = [dictArray valueForKey:#"epoch"];
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:epoches];
for (NSString *string in orderedSet) {
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"epoch == %#", string];
NSArray *resultsArray = [dictArray filteredArrayUsingPredicate:predicate];
[finalArray addObject:resultsArray];
}
Hi you can use the NSPredicate to filter an array like:
//NSPredicate to filter an array
NSArray *data = [NSArray arrayWithObject:[NSMutableDictionary dictionaryWithObject:#"hello" forKey:#"Test"]];
NSArray *filtered = [data filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"(Test == %#)", #"hello"]];
Thanks
It appears that you are using dictionaries along with arrays. Here's what I've achieved:
(result
(data
{
epoch = 1371333600;
},
{
epoch = 1371333600;
}
),
(data
{
epoch = 1371420000;
}
)
)
I'm not using predicates, but it looks as it's working :). Here is the code:
// Initial input
NSArray *result = #[#{#"epoch":#"1371333600"},#{#"epoch":#"1371420000"},#{#"epoch":#"1371333600"}];
// Get unique values for the input
NSSet *resultSet = [NSSet setWithArray:result];
// Here we are going to store the final result
NSMutableArray *newResult = [[NSMutableArray alloc] init];
// Loop over the unique items
for (NSDictionary *uniqueItem in resultSet) {
// Here we are going to store the grouped data
NSMutableArray *dataResult = [[NSMutableArray alloc] init];
// Loop over the initial input
for (NSDictionary *resultItem in result) {
// Search for all the items that are equal to the uniqe
// I would rather include a count instead of repeating values :)
if([uniqueItem isEqual:resultItem]) {
[dataResult addObject:resultItem];
}
}
[newResult addObject:dataResult];
}
NSLog(#"%#", newResult);
Cheers!
I have json data as below.
[
{"id":"2","imagePath":"image002.jpg","enDesc":"Nice Image 2"},
{"id":"1","imagePath":"image001.jpg","enDesc":"Nice Image 1"}
]
I am assigning this to variable named NSArray *news.
Now I have three different array as below.
NSArray *idArray;
NSArray *pathArray;
NSArray *descArray;
I want to assign data of news to these arrays so that finally I should have as below.
NSArray *idArray = #["2","1"];
NSArray *pathArray = #["image002.jpg","image001.jpg"];
NSArray *descArray = #["Nice Image 2","Nice Image 1"];
Any idea how to get this done?
With the help of below answer this is what I did.
pathArray = [[NSArray alloc] initWithArray:[news valueForKey:#"imagePath"]];
I don't wanted to use NSMutableArray for some reasons.
You should use JSONKit or TouchJSON to convert your JSON data to Dictionary.
Than you may do this :
NSArray *idArray = [dictionary valueForKeyPath:#"id"]; // KVO
Use this
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableContainers error:nil];
then you can extract all the information that you need from there you have NSArray that contains NSDictionary , where you can go and use objectForKey: to get all the info you need.
Load the json data into an NSDictionary, which you may call "news" . Then retrieve as
NSArray *idArray = [news valueForKeyPath:#"id"];
NSArray *pathArray = [news valueForKeyPath:#"imagePath"];
NSArray *descArray = [news valueForKeyPath:#"enDesc"];
Yes all the above ans is correct I am just integrating all of them together to be easly use to you:
NSArray *serverResponseArray = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableContainers error:nil]; // I am assigning this json object to an array because as i show it is in array format.
now:
NSArray *idArray = [[NSMutableArray alloc] init];
NSArray *pathArray = [[NSMutableArray alloc] init];
NSArray *descArray = [[NSMutableArray alloc] init];
for(NSDictionary *news in serverResponseArray)
{
[idArray addObject:[news valueForKey:#"id"]];
[pathArray addObject:[news valueForKey:#"imagePath"]];
[descArray addObject:[news valueForKey:#"enDesc"]];
}
I am new to iOS and want to create an NSArray like this which contains an NSDictionary.
[
{
Image: 1, 2,3
Title: 1,2,3
Subtitle:1,2,3
}
]
I have tried this.
NSArray *obj-image=#[#"Test.png",#"Test.png",#"Test.png"];
NSArray *obj-title=#[#"Test",#"Test",#"Test"];
NSArray *obj-subtitle=#[#"Test",#"Test",#"Test"];
NSDictionary * obj_dictionary ={ image : obj_image, title:obj_title, subtitle:obj_subtitle}
NSArray * obj_array= [obj_dictionarry];
But not working and how to access them.
First of all, you initialization of Arrays and Dictionaries is wrong. You cannot use "-" in the names, period.
Second, you need to allocate and then initialize the objects. This is how you do that with arrays:
NSArray *images = [NSArray arrayWithObjects: #"TestImage",#"TestImage",#"TestImage",nil];
NSArray *titles = [NSArray arrayWithObjects: #"TestTitle",#"TestTitle",#"TestTitle",nil];
NSArray *subtitles = [NSArray arrayWithObjects: #"TestSubTitle",#"TestSubTitle",#"TestSubTitle",nil];
Then you need Mutable dictionary and mutable arrays to work with the data (mutable means you can change the values inside, add or remove objects etc.)
This is the most basic example of what you are trying to achieve:
NSArray *images = [NSArray arrayWithObjects: #"TestImage",#"TestImage",#"TestImage",nil];
NSArray *titles = [NSArray arrayWithObjects: #"TestTitle",#"TestTitle",#"TestTitle",nil];
NSArray *subtitles = [NSArray arrayWithObjects: #"TestSubTitle",#"TestSubTitle",#"TestSubTitle",nil];
NSMutableArray *objectsMutable = [[NSMutableArray alloc] init];
for (NSString *string in images) {
NSMutableDictionary *dictMutable = [[NSMutableDictionary alloc] init];
[dictMutable setObject:string forKey:#"image"];
//determining the index of the image
NSInteger stringIndex = [images indexOfObject:string];
[dictMutable setObject:[titles objectAtIndex:stringIndex] forKey:#"title"];
[dictMutable setObject:[subtitles objectAtIndex:stringIndex] forKey:#"subtitle"];
NSDictionary *dict = [[NSDictionary alloc] init];
dict = dictMutable;
[objectsMutable addObject:dict];
}
NSArray *objects = objectsMutable;
NSLog(#"%#", objects);
Hope this helps.
As you can see, I'm going through the images array, capturing the index of each one, an then just apply values of other arrays from the same index into a mutable dictionary.
All I do after that is just make a regular dictionary and array to put the data inside. This is ho the Log will look:
(
{
image = TestImage;
subtitle = TestSubTitle;
title = TestTitle;
},
{
image = TestImage;
subtitle = TestSubTitle;
title = TestTitle;
},
{
image = TestImage;
subtitle = TestSubTitle;
title = TestTitle;
}
)
You have an array with three objects inside, each with their own image, title and subtitle.
Here is code :
NSMutableArray *array = [[NSMutableArray alloc] init];
NSMutableDictionary *mdict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"object1",#"key1",#"object2",#"key2",nil];
[array addObject:mDict];
so now if u need to access dictionary from array then :
NSMutableDictionary *mDict1 = [array objectatindex:0];
NSLog(#"%#",[mDict1 valueForkey:#"key1"];
--> print object 1.
This is the way to store array of dictionaries:
NSDictionary *dic=#{#"kishore":#"hai"};
NSMutableArray *arr=[[NSMutableArray alloc]init];
[arr addobject:dic];
this is the way to get those values:
[arr objectforkeyValue #"kishore"];
NSMutableArray *dictArray = [[NSMutableArray alloc] init]; // created and initiated mutable array
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init]; // created and initiated mutable Dictionary
[dict setObject:#"object1" forKey:#"1"]; // added a key pair in dictionary (you can set multiple objects)
[dictArray addObject:dict]; // added dictionary to array (you can add multiple dictionary to array )
NSLog(#"dictionary inside an array : %#",dictArray[0][#"1"]); // access dictionary from array
You can try something like this
[NSArray arrayWithObjects:#{#"Image":#[#1,#2,#3]},#{#"Title":#[#1,#2,#3]},#{#"SubTitle":#[#1,#2,#3]}, nil];
You can easily create objects of array and access them back using following way.
NSArray *objimage=#[#"Test1.png",#"Test2.png",#"Test3.png"];
NSArray *objtitle=#[#"Test1",#"Test2",#"Test3"];
NSArray *objsubtitle=#[#"Test1",#"Test2",#"Test3"];
NSDictionary *obj_dictionary = #{#"image":objimage,#"Title":objtitle, #"subtitle":objsubtitle};
NSArray * obj_array= [[NSArray alloc] initWithObjects:obj_dictionary, nil]; // Create Array of nested objects
if([obj_array count] > 0) {
NSArray * imageArray = obj_array[0][#"image"]; // Access the nested objects in Array.
NSLog(#"%#", imageArray[0]);
}
first of all u need to declare correct variable name
NSArray *objImage=#[#"Test.png",#"Test.png",#"Test.png"];
NSArray *objTitle=#[#"Test",#"Test",#"Test"];
NSArray *objSubtitle=#[#"Test",#"Test",#"Test"];
at this point all u are created all the array, and u need to create dictionary like below
NSDictionary *obj_dictionary = #{#"image":objImage,#"title":objTitle, #"subtitle":objSubtitle};
// NSArray * obj_array = obj_dictionary[#"image"];
NSArray * obj_array = #[obj_dictionary]; //u can crate array of dictionary like this
in above obj_dictionary will contains all the array like below,
Title = (
Test,
Test,
Test
);
image = (
"Test.png",
"Test.png",
"Test.png"
);
subtitle = (
Test,
Test,
Test
);
and u can access the object in the dictionary like below using a key for example
NSArray * obj_array_images = obj_dictionary[#"image"];
gives an array of images that is associated with key image, similarly u can access other array like this by providing different keys associated with the dictionary obj_dictionary for example
NSArray * obj_array_titles = obj_dictionary[#"title"];
NSArray * obj_array_subtitles = obj_dictionary[#"subtitle"];
edit
NSArray *objImage=#[#"Test.png",#"Test.png",#"Test.png"];
NSArray *objTitle=#[#"Test",#"Test",#"Test"];
NSArray *objSubtitle=#[#"Test",#"Test",#"Test"];
NSDictionary *obj_dictionary = #{#"image":objImage,#"title":objTitle, #"subtitle":objSubtitle};
// NSArray * obj_array = obj_dictionary[#"image"];
NSArray * obj_array = #[obj_dictionary]; //u can crate array of dictionary like this