Sort Dictionary of Array Using Predicate - ios

I have a json dictionary
[
{
"allquestions": [
{
"question": "First question in 0th index"
},
{
"question": "Second question in 0th index"
}
]
},
{
"allquestions": [
{
"question": "First question in 1st index"
}
]
}
]
I need to get all values of key allquestions in single array using predicate.
I have tried so far is
NSPredicate *combinePagePredicate = [NSPredicate predicateWithFormat:#"allquestions == %#",#"someValue"];
What will be the value of someValue to solve my problem?

Not entirely sure what your trying to achieve. If you want a list of all of the questions in that dictionary then iterate through each dictionary separately and then the same for the questions. Add the questions to an array and then filter that array. Not tried this code out but it's a start.
NSMutableArray *questions = [[NSMutableArray alloc] init];
for (id i in dictionaryArray)
{
NSArray *arr = i[#"allquestions"];
for (id x in arr)
{
NSString *currentQuestion = [x objectForKey:#"question"];
[questions addObject:currentQuestion];
}
}

Related

Create dictionary with dictionaries of arrays (sorted by a specific custom object property)?

The title may be confusing, apologies. Maybe someone can advise me on a more appropriate title.
I have a .json file structured as below.
"sections": [{
"title": "Locations",
"key": "location"
}],
"contacts": [{
"title": "Social Worker",
"name": "Mrs X",
"office": "xxxxxxxx",
"location": "Lisburn",
"department": "xxxxxxxx",
"telephone": "xxx xxxxxxxx"
},...
When parsing this, I create an array called contactsArray. I can then create AEContact objects from this array like so:
for (NSDictionary *contactDic in [contactsArray valueForKey:#"contacts"]) {
// Create AEContact objects
_contact = [[AEContact alloc] initWithDictionary:contactDic];
[contacts addObject:_contact];
}
self.contacts = [contacts copy];
In the self.contacts array, the value for the contact.location property is what I am interested in. I need to create separate arrays of related AEContact objects based on the location property, then map these to the location key in my contactArray dictionary
This is what I have tried so far:
NSMutableDictionary *locationsDic = [NSMutableDictionary new];
// Loop through contacts
for (int i = 0; i < self.contacts.count; i++) {
// Sort by location
if ([self.contacts[i] valueForKey:#"location"] == [[[contactsArray valueForKey:#"contacts"] objectAtIndex:i] valueForKey:#"location"]) {
[locationsDic setValue:self.contacts[i] forKey:[[[contactsArray valueForKey:#"contacts"] objectAtIndex:i] valueForKey:#"location"]];
}
}
And the output is:
{
Ballynahinch = "<AEContact: 0x15dda1fc0>";
Bangor = "<AEContact: 0x15dda2210>";
Lisburn = "<AEContact: 0x15dda1c70>";
...
}
When an AEContact object has the same location, it sets it as another key/value in the dictionary and overwrites the previous entry. What I need to happen is something like this:
{
Lisburn = "<AEContact: 0x15dda18f0>",
"<AEContact: 0x15dda18f0>",
"<AEContact: 0x15dda18f0>";
Bangor = "<AEContact: 0x15dda18f0>",
"<AEContact: 0x15dda18f0>",
"<AEContact: 0x15dda18f0>";
}
I'm not sure if the output should should/will look like the preview above, I can only assume as I have not yet achieved my goal. How can I create the related AEContact objects in an array and map them to location key in my locationsDic? Thanks.
The title (and the problem description) are a little tough to follow, but I think you're trying to index an array of (AEContact) objects by their location parameter.
We can clarify this just with some tighter naming and with a find-or-create pattern as we process the input.
NSDictionary *jsonResult = // the dictionary you begin with
NSArray *contactParams = jsonResult[#"contacts"];
NSMutableDictionary *contactsByLocation = [#{} mutableCopy];
for (NSDictionary *contactParam in contactParams) {
NSString *location = contactParam[#"location"];
// here's the important part: find the array of aecontacts in our indexed result, or
// create it if we don't find it
NSMutableArray *aeContacts = contactsByLocation[location];
if (!aeContacts) {
aeContacts = [#[] mutableCopy];
contactsByLocation[location] = aeContacts;
}
AEContact *aeContact = [[AEContact alloc] initWithDictionary:contactParam];
[aeContacts addObject:aeContact];
}
contactsByLocation will be what I think you're looking for.

How to get Array inside fields from JSON Structure in ios

Hi i am beginner in ios and in my project i am integrating services with my app but i am struggling to integrate some service fields with my app
Please see below JSON structure there i want to get all "languages" Array inside elements but i am not understand how to get those fields please help me some one
Json stucture:-
- loans: [

 - {
id: 983381,
name: "America",
description: 
 {
languages: 
 [
"English"
]
},
},
- {
id: 983382,
name: "Jarmani",
description: 
 {
languages: 
 [
"Jarman"
]
},
},
- {
id: 983383,
name: "Rasya",
description: 
 {
languages: 
 [
"Rasya"
]
},
},
]
my code:-
NSMutableArray * array1 = [mainDictyionary objectForKey:#"loans"];
for (NSDictionary * obj in array1) {
MainArray = [obj objectForKey:#"languages"];
}
NSLog(#"so finally array values are %#",MainArray);
You want to
Declare MainArray as a NSMutableArray: MainArray = [[NSMutableArray alloc] init];
Now you will be adding the "languages" NSArrays to a 'mother-array', I'm guessing that is not what you want
So you want to iterate over the [obj objectForKey:#"languages"] array and call addObject on the MainArray for every NSString value you'll encounter in the [obj objectForKey:#"languages"]-iteration.
You'll end up with a mutable NSArray that has all the languages in it, as NSStrings
Actually you are getting the value upto languages and not upto "english" or anyother. And also you are assigning the values to MainArray, so it will not add all the values it will add last value of the loop.
NSMutableArray * array1 = [mainDictyionary objectForKey:#"loans"];
NSMutableArray *MainArray = [NSMutableArray alloc] init];
for (NSDictionary * obj in array1) {
NSDictionary *descriptionDictionary = [obj objectForKey:#"description"];
[MainArray addObject:[obj objectForKey:#"languages"]];
}
NSLog(#"so finally array values are %#", MainArray);

Xcode - Getting object out of an array within an array

I have a JSON array(dictionary?) of objects that are themselves an array. I need to find a value within one of these arrays so that I can compare it later. Part of my JSON data:
[
{
"Name": "Exhibitor",
"Url": "api/congress/exhibitor",
"ResourceType": "Data",
"LastMod": 1389106977
},
{
"Name": "Workshop",
"Url": "api/congress/workshop",
"ResourceType": "Data",
"LastMod": 1389106977
},
{
"Name": "Speaker",
"Url": "api/congress/Speaker",
"ResourceType": "Data",
"LastMod": 1389106977
},
]
My method receives a table name as a parameter and returns a time stamp. How would I receive the time stamp (1389106977) for the table "workshop" for example? This seems so simple but I cannot work it out for 'nested' arrays/dictionaries.
Thanks,
edit:
This is the my code with trojanfoe's added to it.
NSError* localError;
NSMutableArray *syncDataArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if (syncDataArray)
{
NSNumber *lastMod = nil;
for (NSDictionary *dict in syncDataArray)
{
NSLog(#"current table is: %#", dict[#"Name"]);
if ([tableName isEqualToString:dict[#"Name"]])
{
lastMod = dict[#"LastMod"];
//break;
}
}
NSLog(#"LastMod = %#", lastMod);
}
else
{
NSLog(#"syncDataArray is empty");
}
This works perfectly and makes sense
The JSON data looks like an array of dictionaries, so you can iterate over the array and test for the "Name" entry:
NSArray *jsonData = ...; // You have converted JSON to Objective-C objects already
NSNumber *lastMod = nul;
for (NSDictionary *dict in jsonData) {
if ([#"Workshop" isEqualToString:dict[#"Name"]]) {
lastMod = dict[#"LastMod"];
break;
}
}
if (lastMod) {
// You found it
}
(Note I am not certain the type of object used to store the "LastMod" object, so you might need to do some debugging to find out).
EDIT If you make extensive use of this data you should immediately convert the JSON data into an array of (custom) model objects, which will make it easier to manipulate the data as your app becomes more complex.
You have an array for dictionaries so it would look something like :
NSNumber *timestamp = [[JSON objectAtIndex:index] objectForKey:#"LastMod"];
NSNumber *timestamp = response[1][#"LastMod"];

how to get JSON object from server as it (in the same order) iPhone

Is there any way to get JSON object from the server in the same order??
For example when i fitch using browser my JSON object return like this:
{
"23": {
"numberOfRecords": "3",
"startDate": "27/11/2013",
"endDate": "31/12/2014",
"question": "How do you rate the new MenaME Portal ?",
"voteScale": "5",
"questions": {
"option1": {
"value": "1",
"option": "Poor",
"voteResult": "50.000"
},
"option2": {
"value": "2",
"option": "Acceptable",
"voteResult": "0.000"
},
"option3": {
"value": "3",
"option": "Good",
"voteResult": "0.000"
},
"option4": {
"value": "4",
"option": "Very Good",
"voteResult": "0.000"
},
"option5": {
"value": "5",
"option": "Excellent",
"voteResult": "50.000"
}
},
"selectedAnswer": "0",
"voteAnswered": "0",
"votes": "6"
}
}
after parsing it with [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error]
the object returned like this :
{
23 = {
endDate = "31/12/2014";
numberOfRecords = 3;
question = "How do you rate the new MenaME Portal ?";
questions = {
option1 = {
option = Poor;
value = 1;
voteResult = "50.000";
};
option2 = {
option = Acceptable;
value = 2;
voteResult = "0.000";
};
option3 = {
option = Good;
value = 3;
voteResult = "0.000";
};
option4 = {
option = "Very Good";
value = 4;
voteResult = "0.000";
};
option5 = {
option = Excellent;
value = 5;
voteResult = "50.000";
};
};
selectedAnswer = 0;
startDate = "27/11/2013";
voteAnswered = 0;
voteScale = 5;
votes = 6;
};
}
Is there any way or framework to get the object as it (in the same order returned from the server) ??
Dictionaries, both in JSON and NSDictionary, are unordered, meaning that it is irrelevant which order you see things in the log. This is defined in the JSON specification and the documentation for NSDictionary.
If it actually matters what order things are displayed in, then either the API you are linking to isn't using correct JSON, or you're doing something wrong in your app. To help with those situations you can use several of the sorted NSDictionary implementations that are around.
Can I ask why you want to ensure the dictionary is maintained in the correct order?
I understand in some cases (mine) an ancient JSON -> XML web service was being called by my app and the client refused to adjust the service so it could accept unordered JSON (valid json) but if you're writing the app, why do you need to ensure that it is in order?
I have a NSMutableDictionary subclass that keeps objects added by setObject:forKey in the order you call the method that can be found here.
It works by storing a NSMutableOrderedSet of keys within the dictionary and then overrides the keyEnumerator method to return an enumerator based on the ordered set
- (NSEnumerator *)keyEnumerator
{
return [self.orderedSetOfKeys objectEnumerator];
}
You could modify the NSMutableDictionary subclass i created to expose the NSMutableOrderedSet in the public header and then modify this set yourself to get an ordered version of your dictionary.. For example:
NSDictionary *JSONWebServiceDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
LNOrderedMutableDictionary *orderedDictionary = [[LNOrderedMutableDictionary alloc] initWithDictionary:JSONWebServiceDictionary];
NSMutableOrderedSet *order = [[NSMutableOrderedSet alloc] initWithArray:#[#"key1",#"key2",#"key3"]]; //All the keys you are expecting and the order you want them in..
orderedDictionary.orderSet = order; //orderSet does not exist.. it is currently called `array` and not exposed in LNOrderedMutableDictionary.h
I haven't tested the code above but unless you want to create or modify an existing JSON parser then it seems that it is your only option..
If you did want to modify an existing parser then it might just be as simple as replacing dictionary instances with LNOrderedMutableDictionary to keep everything in order.
Another idea to expand the above sample code could be to replace
NSMutableOrderedSet *order = [[NSMutableOrderedSet alloc] initWithArray:#[#"key1",#"key2",#"key3"]];
with an array returned in the JSONWebServiceDictionary dictionary as arrays keep their order when parsed from JSON so maybe you could do this?
NSMutableOrderedSet *order = [[NSMutableOrderedSet alloc] initWithArray:[JSONWebServiceDictionary objectForKey:#"keyOrderArray"]]];
Look at what you have. If you test the result you got back from JSONObjectWithData (which we'll assume was declared as id jsonObject)
if ([jsonObject isKindOfClass:[NSDictionary class]) { ...
or
NSLog(#"The object type is %#", [jsonObject class]);
you will find that it is indeed an NSDictionary (or perhaps an NSMutableDictionary). That dictionary, as you can see from the dump (or infer from the nearly identical JSON) contains a single entry with a key of "23".
So let's cast the jsonObject to an NSDictionary and reference it:
NSDictionary* jsonDict = (NSDictionary*) jsonObject;
NSDictionary* entry23Dict = [jsonDict objectForKey:#"23"];
Now, if you NSLog entry23Dict you will discover it contains all of the above, absent the { 23 = ... } outermost dictionary.
You can then access, say, "questions" with
NSDictionary* questDict = [entry23Dict objectForKey:#"questions"];
From there the individual "option1", "option2", ... "option5" dictionaries can be accessed in a similar fashion. You simply proceed one layer at a time -- don't get overwhelmed by the entire structure. (It's often helpful, when you're first learning, to NSLog each "layer" as you "peel" it out of the containing structure.)
And, of course, you have all the standard facilities that are available to NSDictionary objects (and NSArray objects, should your JSON contain any [..] arrays). For instance, you can iterate on the keys of the dictionary with
for (NSString* key in jsonDict) {
NSLog(#"This entry's number is %#", key); // For the above will print "23"
NSDictionary* numberedDict = jsonDict[key]; // Using the "new" form of dictionary access
NSString* endDate = numberedDict[#"endDate"]; // Ditto
NSLog(#"The end date is %#", endDate);
}
This is a fairly common problem. It's also probably the most annoying part about iOS. (java doesn't have this issue at all). If you want to get back objects, take a look at restkit.org Specifically this answer may help: https://stackoverflow.com/a/8284343/836450

Indexing an NSMutableDictiobary?

I have an NSMutableDictionary which holds objects of string type like this:
{
{
{"ID":"23"},
{"NAME":"Ted"}
},
{
{"ID":"46"},
{"NAME":"Karren"}
},
{
{"ID":"6"},
{"NAME":"Phillip"}
}
}
I need a way to access object with ID #x in an indexed manner.
Now, since the object with ID=46 is in index #1
I need a way to make the dictionary still have it's objects in their index as it is, but is it possible to add a key to that object?
Like:
"6":"{
{"ID":"6"},
{"NAME":"Phillip"}
}"
If possible to show some code.
Otherwise, how can I do that another way.
Thanks
What about using predicates ?
NSArray *resultArray = [[[myDictionary allValues] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"ID == %#", #"6"]];
you retrieve all your dictionary values, and use a predicate to return a single element array with the value you were looking for
(code not tested but should work)
First of all you need to do something with the strucutre,
[
{
"ID": 23,
"Name": "Ted"
},
{
"ID": 46,
"Name": "Karen"
},
{
"ID": 6,
"Name": "Philip"
}
]
This would make your work a lot easier. You can search/sort it based on ID or Name easily.
//All users array
NSArray *users = ....
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"ID = %d",userID];
//Find User against a user id
NSDictionary *user = [[users filteredArrayUsingPredicate:predicate] lastObject];

Resources