How to parse JSON - objective-c

How to parse this below "choices" on one array means when I have get "id" in array that all id values 108,109.... in 1st index in array but here is the 5 values in choices..so how to parse it
choices = (
{
id = 108;
label = Distributor;
},
{
id = 109;
label = "Clinical Lab";
},
{
id = 110;
label = Researcher;
},
{
id = 111;
label = "Current Customer";
},
{
id = 112;
label = "Past Customer";
}
);

Get in a single Step bro as
If your array is NSMutableArray then use as
NSArray *resultArray = [[NSArray arrayWithArray:temp] valueForKeyPath:#"id"]
If simple NSArray then use as
NSArray *resultArray = [jsonArray valueForKeyPath:#"id"]

You can do it using fast enumeration.
NSMutableArray *resultArray = [[NSMutableArray alloc] initWithCapacity:0];
// JSONDict is your JSON dict
for (NSDictionary *aDict in JSONDict[#"choices"]) {
[resultArray addObject:aDict[#"id"]];
}
NSLog(#"%#", resultArray);
Output:
(
108,
109,
110,
111,
112
)

If i understand your question properly, Then You can try this code for getting Ids in a Array:
NSMutableArray *arr = [[NSMutableArray alloc] init];
for (int i = 0;i<[choices count];i++)
{
[arr addObject:[[choices objectAtIndex:i] objectForKey:#"id"]];
}
NSLog(#"ID array : %#",arr);
[arr release];

try like this ,
NSMutableArray *idArray=[[NSMutableArray alloc]init];
for(int i=0;i<[jsonArray count];i++)
[idArray addObject:[[jsonArray objectAtIndex:i] valueForKey:#"id"]];
NSLog(#"%#",idArray);
here you'l get all the values in idArray.

Related

Change json format in NSDictionary (Objective C)

I am new in ios programming. I should apply data to the chart. But the framework(ShinobiControls) which I use accepts only json with certain format. So I have to change my json data format to appropriate. I have NSDictionary which contain json like this:
"data": [
"01.01.2015",
"01.01.2015",
"01.01.2015",
"01.01.2015"]
"close": [
[
1,
1,
1,
1]
And now I should change format of the json like this:
[
{
"date": "01.01.2015",
"close": 1
},
{
"date": "01.01.2015",
"close": 1
},
{
"date": "01.01.2015",
"close": 1
},
{
"date": "01.01.2015",
"close": 1
}
]
I did some manipulation with converting NSDictionary to NSArray, but didn't get anything. How can I do it? Do you have any ideas? Thank you.
So if i understand your question right, you have a dictionary that contains 2 arrays and you want to convert it to an array that contains dictionaries , assuming that that the count of the arrays in the dictionary is equal, you can do the following
//This is the first array in your dictionary
NSArray * dataArr = [data objectForKey:#"data"] ;
//This the second array in your dictionary
NSArray * closeArr = [data objectForKey:#"close"] ;
NSUInteger dataCount = [dataArr count] ;
NSUInteger closeCount = [closeArr count] ;
//This will be your result array
NSMutableArray * newData = [NSMutableArray new] ;
//The loop condition checks that the current index is less than both the arrays
for(int i = 0 ; i<dataCount && i<closeCount ; i++)
{
NSMutableDictionary * temp = [NSMutableDictionary new] ;
NSString * dataString = [dataArr objectAtIndex:i];
NSString * closeString = [closeArr objectAtIndex:i];
[temp setObject:dataString forKey:#"date"];
[temp setObject:closeString forKey:#"close"] ;
[newData addObject:temp];
}
NSArray *Arr = [[NSArray alloc] initWithObjects:#"01.01.2015",#"01.01.2015",#"01.01.2015",#"02.01.2015", nil];
NSArray *Arr1 = [[NSArray alloc] initWithObjects:#"1",#"1",#"1",#"1", nil];
NSDictionary *Dic = [[NSDictionary alloc] initWithObjectsAndKeys:Arr,#"data",Arr1,#"close", nil];
NSLog(#"%#",Dic);
NSMutableArray *ArrM = [[NSMutableArray alloc] init];
for ( int i = 0; i<Arr.count; i++) {
NSDictionary *Dic = [[NSDictionary alloc] initWithObjectsAndKeys:Arr[i],#"data",Arr1[i],#"close", nil];
[ArrM addObject:Dic];
}
NSLog(#"%#",ArrM);
NSError * err;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:ArrM options:0 error:&err];
NSString * myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"%#",myString);

Create array of dictionary with different keys?

I have following array,I have one array with multiple dictionaries,I need to get that dictionaries for same prod_type and create another array with unique key
nsarray
{
{
prod_type=abc;
fund=100;
};
{
prod_type=abc;
fund=100;
};
{
prod_type=abc;
fund=100;
};
{
prod_type=pqr;
fund=100;
};
{
prod_type=pqr;
fund=100;
};
{
prod_type=xyz;
fund=100;
};
{
prod_type=xyz;
fund=100;
};
I need following array format from above array
nsarray=
{
abc=
{
{
prod_type=abc;
fund=100;
};
{
prod_type=abc;
fund=100;
};
{
prod_type=abc;
fund=100;
};
}
pqr=
{
{
prod_type=pqr;
fund=100;
};
{
prod_type=pqr;
fund=100;
};
}
xyz=
{
{
prod_type=xyz;
fund=100;
};
{
prod_type=xyz;
fund=100;
};
}
}
Use NSPredicate to get desirable result.
NSString *selectedCategory=#"abc";
//filter array by category using predicate
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"prod_type == %#", selectedCategory];
NSArray *filteredArray = [yourAry filteredArrayUsingPredicate:predicate];
NSDictionary *abcDic = [NSDictionary dictionaryWithObject:filteredArray forKey:#"abc"];
[yourNewAry addObject:abcDic];
You can repeat it for other
Here a nice explanation of it predicates
Use this code if you want a fully automated solution (without having to re-specify each prod_type):
NSMutableArray *keys = [originalArray mutableArrayValueForKey:#"prod_type"];
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:keys];
NSArray *uniqueKeys = orderedSet.array;
NSMutableArray *resultArray = [[NSMutableArray alloc] init];
for(NSString *key in uniqueKeys){
NSPredicate *keyPredicate = [NSPredicate predicateWithFormat:#"prod_type = %#",key];
NSDictionary *keyDictionary = [NSDictionary dictionaryWithObject:[originalArray filteredArrayUsingPredicate:keyPredicate] forKey:key];
[resultArray addObject:keyDictionary];
}
NSLog(#"%#",resultArray);
try like this,
NSMutableDictionary *resultdict = [[NSMutableDictionary alloc]init];
NSMutableArray *keysArray =[array mutableArrayValueForKey:#"prod_type"];//here you'l get all the prod_type values in an array
for(int i=0;i<[keysArray count];i++){
NSPredicate *resultPredicate=[NSPredicate predicateWithFormat:#"prod_type CONTAINS %#",[keysArray objectAtIndex:i]];
NSArray* searchResults=[array filteredArrayUsingPredicate:resultPredicate];
[resultdict setObject:searchResults forKey:[keysArray objectAtIndex:i]];
}
NSLog(#"%#",resultdict);
EX:-
NSMutableArray *array =[[NSMutableArray alloc]init];
NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithObjects:#[#"abc",#"100"] forKeys:#[#"name",#"value"]];
NSMutableDictionary *dict1 = [[NSMutableDictionary alloc]initWithObjects:#[#"pqr",#"100"] forKeys:#[#"name",#"value"]];
NSMutableDictionary *dict2 = [[NSMutableDictionary alloc]initWithObjects:#[#"pqr",#"100"] forKeys:#[#"name",#"value"]];
[array addObject:dict];
[array addObject:dict1];
[array addObject:dict2];
NSLog(#"%#",array);
(
{
name = abc;
value = 100;
},
{
name = pqr;
value = 100;
},
{
name = pqr;
value = 100;
}
)
NSMutableDictionary *resultdict = [[NSMutableDictionary alloc]init];
NSMutableArray *keysArray =[array mutableArrayValueForKey:#"name"];
for(int i=0;i<[keysArray count];i++){
NSPredicate *resultPredicate=[NSPredicate predicateWithFormat:#"name CONTAINS %#",[keysArray objectAtIndex:i]];
NSArray* searchResults=[array filteredArrayUsingPredicate:resultPredicate];
[resultdict setObject:searchResults forKey:[keysArray objectAtIndex:i]];
}
NSLog(#"%#",resultdict);
{
abc = (
{
name = abc;
value = 100;
}
);
pqr = (
{
name = pqr;
value = 100;
},
{
name = pqr;
value = 100;
}
);
}

NSArray and NSDictionary

I have NSDictionaries in NSArray just like below.
array(dictionary("user":1, "p1":1), dictionary("user":2, "p1":3),
dictionary("user":1, "p1":5), dictionary("user":2, "p1":7))
And I want to turn this array into dictionary like below.
NSArray *u1 = [NSArray arrayWithObjects:#"1", #"5", nil];
NSArray *u2 = [NSArray arrayWithObjects:#"3", #"7", nil];
keys = [NSArray arrayWithObjects:#"u1", #"u2", nil];
points = [NSDictionary dictionaryWithObjectsAndKeys:u1, #"u1", u2, #"u2", nil];
How can I do that? I am lost, can you guys please help me?
Couldn't you just iterate over your original array, asking each dictionary if the object for key "user" is 1, and if so, copy the object into a new array at index 0? Or if your user numbers are in counting order, maybe even have the index number equal the user number. Then repeat for "user" = 2, etc. Then make a dictionary so that each key/object pair is created by keys from the keys array (keys[i]) and objects from your new array (objects[i]).
What have you tried?
Here is some code typed directly into the answer, so it has not be tested:
You haven't given a name for your original array, so let's assume it is:
NSArray *originalArray;
We need a mutable dictionary to store the result:
NSMutableDictionary *points = [NSMutableDictionary new];
Now we need to process every element in the original array and it is a dictionary:
for(NSDictionary *item in originalArray)
{
Get the current entry in points array that matches item. You don't give types for your entries, so we'll use id:
id currentUser = [item objectForKey:#"user"];
NSMutableArray *currentValues = [points objectForKey:currentUser];
If this is the first occurrence of currentUser then currentValues will be nil, and we need to create an array for the p1 value and add it to points:
if (currentValues == nil)
[points addObject:[NSMutableArray arrayWithObject:[item objectForKey:#"p1"]
forKey:currentUser
]
]
Otherwise we just add the p1 value to the array:
else
[currentValues setObject:[item objectForKey:#"p1"]];
close out the loop and get the keys:
}
NSArray *keys = [points allKeys];
Now if you're using Xcode 4.5 you can use modern syntax for some of that:
NSMutableDictionary *points = [NSMutableDictionary new];
for(NSDictionary *item in originalArray)
{
id currentUser = item[#"user"];
NSMutableArray *currentValues = points[currentUser];
if (currentValues == nil)
points[currentUser] = [NSMutableArray arrayWithObject:item[#"p1"];
else
[currentValues addObject:item[#"p1"]];
}
NSArray *keys = [points allKeys];
HTH
Another possible solution (works with an arbitrary number of users):
NSArray *orig = #[
#{#"user" : #"1", #"p1" : #"1"},
#{#"user" : #"2", #"p1" : #"3"},
#{#"user" : #"1", #"p1" : #"5"},
#{#"user" : #"2", #"p1" : #"7"},
];
// Create set of all users (without duplicates)
NSSet *users = [NSSet setWithArray:[orig valueForKey:#"user"]];
NSMutableDictionary *points = [NSMutableDictionary dictionary];
for (NSString *user in users) {
// newKey = "u" + username, e.g. "u1" or "u2":
NSString *newKey = [#"u" stringByAppendingString:user];
// newValue = array of "p1" values of the current user:
NSPredicate *pred = [NSPredicate predicateWithFormat:#"user == %#", user];
NSArray *newValue = [[orig filteredArrayUsingPredicate:pred] valueForKey:#"p1"];
// Add to dictionary:
[points setObject:newValue forKey:newKey];
}
NSLog(#"%#", points);
Output:
{
u1 = (
1,
5
);
u2 = (
3,
7
);
}
And the keys can be obtained by
NSArray *keys = [points allKeys];
You can do, like this (code not tested)
NSMutableArray *keys=[NSMutableArray new];
NSMutableArray *u1=[NSMutableArray new];
NSMutableArray *u2=[NSMutableArray new];
NSMutableDictionary *points=[NSMutableDictionary new];
for (id dict in array){
NSString *user=[dict objectForKey:#"user"];
NSString *p1=[dict objectForKey:#"p1"];
[keys addObject:[NSString stringWithFormat:#"%#",user]];
if( [user isEqualToString:#"1"] ){
[u1 addObject:user];
}
else{
[u2 addObject:user];
}
}
points=[NSDictionary dictionaryWithObjectsAndKeys:u1,#"u1",u2, #"u2", nil];
Tons of approaches. Here's another:
NSArray *originalArray = #[
#{#"user":#"u1", #"p1":#"1"},
#{#"user":#"u2", #"p1":#"3"},
#{#"user":#"u1", #"p1":#"5"},
#{#"user":#"u2", #"p1":#"7"}
];
NSLog(#"originalArray = %#", originalArray);
NSMutableDictionary *results = [NSMutableDictionary dictionary];
for (NSDictionary *dictionary in originalArray) {
NSString *user = dictionary[#"user"];
NSString *p1 = dictionary[#"p1"];
if (!results[user])
results[user] = [NSMutableArray array];
[results[user] addObject:p1];
}
NSLog(#"results = %#", results);
That takes:
originalArray = (
{
p1 = 1;
user = u1;
},
{
p1 = 3;
user = u2;
},
{
p1 = 5;
user = u1;
},
{
p1 = 7;
user = u2;
}
)
And gives
results = {
u1 = (
1,
5
);
u2 = (
3,
7
);
}

Get values from an Array and calc

I have an array width this values:
array: (
{
id = 1;
name = "Cursus Nibh Venenatis";
value = "875.24";
},
{
id = 2;
name = "Elit Fusce";
value = "254.02";
},
{
id = 3;
name = "Bibendum Ornare";
value = "123.42";
},
{
id = 4;
name = "Lorme Ipsim";
value = "586.24";
}
)
What I need to do is get each 'value' and sum it all. Im declaring a new array to take each value:
self.valuesArray = [[NSArray alloc] init];
But how can I do it? Thanks for your answer!
double sum = [[array valueForKeyPath:#"#sum.value"] doubleValue];
You can read more on collection operators here
You have already declared array so i will use your. I also assume your first array(which contains data set above) is an array called myFirstArray(of type NSArray)
int sum =0;
self.valuesArray = [[NSMutableArray alloc] init];
for(NSDictionary *obj in myFirstArray){
NSString *value =[obj objectForKey:#"value"];
sum+= [value intValue];
[self.valuesArray arrayWithObject:value];//this line creates a new NSArray instance which conains array of 'values'(from your dictionary)
}
NSLog("The sum of values is: %d", sum);
NSLog("The array of \'values\' is : %#",self.valuesArray );
double sum=0.0;
for (YourDataObject *d in array) {
sum+=[[d getValue] doubleValue];
}
try this -
float totalValue = 0.0f;
for (int i = 0 ; i< [array count]; i++) {
totalValue +=[[[array objectAtIndex:i] objectForKey:#"value"] floatValue];
}

Parse nested JSON Object in Objective-C

Perhaps I am over-thinking or confusing myself, but my head is stuck in a loop over this and I cannot break out.
I have a a JSON of the format: (Validated at http://jsonformatter.curiousconcept.com/)
{
id: 1,
sections: "5",
total: "10",
result: {
3: 00PM: [
{
name: "Anurag",
status: "Web"
},
{
name: "Anurag2",
status: "Web2"
}
],
5: 00PM: [
{
name: "Anurag",
status: "Seated"
}
],
6: 00PM: [
{
name: "Anurag4",
status: "Web4"
},
{
name: "Anurag5",
status: "Web5"
},
{
name: "Anurag6",
status: "Web6"
},
{
name: "Anurag7",
status: "Web7"
}
]
}
}
I have this so far:
NSDictionary *dict = [response JSONValue];
NSDictionary *results = [dict objectForKey:#"result"];
NSInteger num_results = [[dict valueForKey:#"total"] intValue];
NSInteger num_sections = [[dict valueForKey:#"sections"] intValue];
NSMutableArray *sections = [[NSMutableArray alloc] initWithCapacity:num_sections];
NSMutableArray *objarr = [[NSMutableArray alloc] initWithCapacity:num_results];
NSMutableArray *obj= [[NSMutableArray alloc] initWithCapacity:num_sections];
NSMutableArray *temp = [[NSMutableArray alloc] initWithCapacity:num_results];
for (NSString* key in results) {
NSLog(#"Key: %#", key); // prints out 3:00 PM...5:00 PM etc...
[obj addObject:[results objectForKey:key]]; // nested objects within each key are saved in the array
NSLog(#"Object 1: %#", obj);
}
for (int i = 0; i < [obj count]; i++) {
//NSLog(#"Object 2: %#", [obj objectAtIndex:i]);
[temp addObject:[obj objectAtIndex:i]]; // I take each object from previous array and save it in a temp array
for (int i = 0; i < num_results; i++) {
NSLog(#"Object 3: %#", [temp objectAtIndex:i]);
**[objarr addObject:[temp objectAtIndex:i]]; // I want to extract the object within the object but cannot get it to work**
}
}
I am able to make an array of objects within each of the 3 keys inside results. But I am not able to get each of the objects inside them as a separate object and save them in an array.
For example, in an NSArray I have:
Object 3: (
{
name = "Anurag ";
status = Web;
},
{
name = "Anurag ";
status = Web;
}
)
How can I get the two objects inside this object and save them both in an array?
I guess the main issue is I cannot refer to a key name to get the individual object.
You can use the following code,
NSDictionary *json = [response JSONValue];
// Get the objects you want
NSArray *items = [json valueForKeyPath:#"result.6: 00PM"];
This will return an NSArray with the objects for the key 6: 00PM
Please check this link too.
You are redefining int i in your second for loop. Try something like
for(int j = 0; j < num_results; j++)
[temp addObject:[obj objectAtIndex:i]]; // I take each object from previous array and save it in a temp array
This is useless motion. You're effectively just copying the obj array to the temp array -- no value added.