How to get array object values from JSON response? - objective-c

I have a json response in this format please look at this.I want to get lat and long values for every address.
{
"message":"success",
"data":
{
"docs":
[
{
"_id":"573d8eca67c7f172cc88387e",
"user":
{
"phone":"8510932519)/+",
"image":"",
"name":"Niraj#%"
},
"distance":18825,
"bookingNumber":"42aopy2dyry8",
"bookingType":0,
"paymentMode":"Card",
"tip":0,
"estimatedFare":51.1,
"estimatedDuration":"2364",
"created":"2016-05-18T14:49:31.231Z",
"stop2":
{
"address":"Malviya Nagar, New Delhi, Delhi 110017, India",
"location":[28.533519700000003,77.21088569999999]
},
"stop1":
{
"address":"Ansari Nagar East, New Delhi, Delhi 110029, India",
"location":
[
28.566540099999997,
77.2098409
]
},
"destination":
{
"address":"Saket, New Delhi, Delhi 110017, India",
"location":
[
28.524578699999996,
77.206615
]
},
"currentLocation":
{
"address":"26, Ashok MargJ Block, Pocket J, Sector 18",
"location":
[
28.568437,
77.32404
]
}
}
],
"total":1,
"limit":8,
"page":":1",
"pages":1
}
}
i need to get lat and long for every address. i am using this code for get the address, but how will i get lat and long for 0 and 1 index in location array?
dictionary = [[NSJSONSerialization JSONObjectWithData:data options:0 error:nil]objectForKey:#"data"];
NSArray *IDArray = [dictionary objectForKey:#"docs"];
for (NSDictionary *Dict in IDArray)
{
NSMutableDictionary *temp = [NSMutableDictionary new];
[temp setObject:[Dict objectForKey:#"_id"] forKey:#"_id"];
NSString *booknumber = [Dict objectForKey:#"bookingNumber"];
if([booknumber length] != 0)
[temp setObject:booknumber forKey:#"bookingNumber"];
NSMutableDictionary *stp1 = [Dict objectForKey:#"stop1"];
if ([[stp1 allKeys] containsObject:#"address"]) {
[temp setObject:[stp1 objectForKey:#"address"] forKey:#"address"];
}
NSMutableDictionary *stp2 = [Dict objectForKey:#"stop2"];
if ([[stp2 allKeys] containsObject:#"address"]) {
[temp setObject:[stp2 objectForKey:#"address"] forKey:#"address1"];
}
NSMutableDictionary *currentloc = [Dict objectForKey:#"currentLocation"];
if ([[currentloc allKeys] containsObject:#"address"]) {
[temp setObject:[currentloc objectForKey:#"address"] forKey:#"address1"];
}

try this
NSMutableDictionary *stp1 = [Dict objectForKey:#"stop1"];
if ([[stp1 allKeys] containsObject:#"address"]) {
[temp setObject:[stp1 objectForKey:#"address"] forKey:#"address"];
// take one Temp array for fetch lat and long
NSArray *tempstp1 = [stp1 objectForKey:#"location"];
[temp setObject:[tempstp1 objectAtIndex:0] forKey:#"latitude"];
[temp setObject:[tempstp1 objectAtIndex:1] forKey:#"longitude"];
}
NSMutableDictionary *stp2 = [Dict objectForKey:#"stop2"];
if ([[stp2 allKeys] containsObject:#"address"]) {
[temp setObject:[stp2 objectForKey:#"address"] forKey:#"address"];
// take one Temp array for fetch lat and long
NSArray *tempstp2 = [stp2 objectForKey:#"location"];
[temp setObject:[tempstp2 objectAtIndex:0] forKey:#"latitude"];
[temp setObject:[tempstp2 objectAtIndex:1] forKey:#"longitude"];
}

Related

i have a json data and i only return a captains on that data dynamically

{
"team":
{
"players":
{
"1":
{
"teamName":"Royal Challenge Bangalore",
"shortName":"RCB",
"11":{
"name":"Virat Kholi",
"Iscaptain":true,
"postion":"2",
"runs":"6000"
},
"12":{
"name":"Chris Gyale",
"postion":"1",
"runs":"4000"
},
"13":{
"name":"AB",
"postion":"4",
"runs":"5000"
}
},
"2":
{
"teamName":"Kolkatta Knight Riders",
"shortName":"KKR",
"11":{
"name":"Robin Uttapa",
"postion":"1",
"runs":"6000"
},
"12":{
"name":"Sunil Narayan",
"postion":"2",
"runs":"4000"
},
"13":{
"name":"Gautam Ganmbhir",
"Iscaptain":true,
"postion":"4",
"runs":"5000"
}
}
}
}
}`enter code here`
You can do it this way. captains will contain NSDictionary objects with related data
NSString *json = #"your json here...";
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:[json dataUsingEncoding:NSUTF8StringEncoding]
options:0
error:&error];
if (error) {
// TODO: handle error...
}
NSArray *teams = [[[dict objectForKey:#"team"] objectForKey:#"players"] allObjects];
NSMutableArray *captains = [NSMutableArray new];
for (NSDictionary *team in teams) {
for (id item in [team allValues]) {
if ([item isKindOfClass:[NSDictionary class]]) {
if ([(NSDictionary *) item objectForKey:#"Iscaptain"]) {
[captains addObject:item];
}
}
}
}

Split an NSArray in smaller key value coded arrays using a common key-value pair between objects

I'm trying to find a good solution to split an array of dictionaries in a smaller dictionaries keyed by a common value between them.
Here is an example i JSON, I start from this:
{
"field": [
{
"id": 6,
"name": "Andrea"
},
{
"id": 67,
"name": "Francesco"
},
{
"id": 8,
"name": "Maria"
},
{
"id": 6,
"name": "Paolo"
},
{
"id": 67,
"name": "Sara"
}
]
}
I'd like to get a result like:
{
"field": [
{
"6": [
{
"name": "Andrea",
"id": 6
},
{
"name": "Paolo",
"id": 6
}
],
"67": [
{
"name": "Sara",
"id": 67
},
{
"name": "Francesco",
"id": 67
}
],
"8": [
{
"name": "Maria",
"id": 8
}
]
}
]
}
I managed using this code, it works, but I'm wondering if exist something more correct and fast:
NSArray * array = ...;
NSSortDescriptor *sorter1=[[NSSortDescriptor alloc]initWithKey:#"id" ascending:YES selector:#selector(compare:)];
NSSortDescriptor *sorter2=[[NSSortDescriptor alloc]initWithKey:#"name" ascending:YES selector:#selector(caseInsensitiveCompare:)];
NSArray *sortDescriptors=[NSArray arrayWithObjects:sorter1,sorter2,nil];
array = [array sortedArrayUsingDescriptors:sortDescriptors];
//////////////////////////////SPLITTER
NSMutableArray * subcategorySplittedArray = [[NSMutableArray alloc]initWithCapacity:30];
NSNumber * lastID=[[array objectAtIndex:0]objectForKey:#"id"];
NSMutableArray * shopArray = [[NSMutableArray alloc]initWithCapacity:100];
NSMutableDictionary * catDict = nil;
for (NSDictionary * dict in array) {
NSNumber * catID = [dict objectForKey:#"id"];
if ([lastID isEqualToNumber:catID]) {
[shopArray addObject:dict];
}
else {
catDict = [[NSMutableDictionary alloc]init ];
[catDict setObject:[shopArray copy] forKey:lastID];
[subcategorySplittedArray addObject:catDict];
[shopArray removeAllObjects];
[shopArray addObject:dict];
lastID = catID;
}
}
catDict = [[NSMutableDictionary alloc]init ];
[catDict setObject:[shopArray copy] forKey:lastID];
[subcategorySplittedArray addObject:catDict];
////////////////////////////////////
return subcategorySplittedArray;
}
NSMutableDictionary* result = [NSMutableDictionary dictionary];
NSArray* ids = [array valueWithKey:#"id"];
NSSet* uniqueIDs = [NSSet setWithArray:ids];
for (NSNumber* anID in uniqueIDs)
{
NSPredicate* pred = [NSPredicate predicateWithFormat:#"id == %#", anID];
NSArray* dictsForID = [array filteredArrayUsingPredicate:pred];
[result setObject:dictsForID forKey:anID];
}
If there are lots of IDs, you may be able to speed this up a bit by building a predicate with a variable reference outside of the loop and then just substituting the variable in to produce the id-specific predicate for each pass through the loop.
By the way, in your question, the result "field" is still an array for some reason. I don't think it needs to be.
Updated to make just one pass:
NSMutableDictionary* result = [NSMutableDictionary dictionary];
for (NSDictionary* dict in array)
{
NSNumber* anID = [dict objectForKey:#"id"];
NSMutableArray* resultsForID = [result objectForKey:anID];
if (!resultsForID)
{
resultsForID = [NSMutableArray array];
[result setObject:resultsForID forKey:anID];
}
[resultsForID addObject:dict];
}

Can't access to inner nodes in JSON message - IOS

I'm trying to access "node" node for this JSON message:
{
"nodes": [
{
"node": {
"title": "Jornada del FĂștbol Profesional contra el hambre",
"description": "
"image": "",
"fecha": "",
"nid": "",
"noticia_relacionada_1_path": "",
"noticia_relacionada_2_path": "",
"image_small_2": ""
}
}
]
}
With this code:
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *results = [responseString JSONValue];
NSDictionary *nodes = [results objectForKey:#"nodes"];
results dictionary has 1 key result. nodes dictionary has 10 keys result. But when I try to access for node with all of this options, I got no results:
NSString *node = [nodes valueForKey:#"node"];
NSArray *nodeArray = [nodes objectForKey:#"node"];
NSDictionary *nodeDic = [nodes objectForKey:#"node"];
Many thanks
The object you retrieve with
NSDictionary *nodes = [results objectForKey:#"nodes"];
is not a dictionary, it is an array of dictionaries, each with one entry with the key "node". To get the first node:
NSArray *nodes = [results objectForKey:#"nodes"];
NSDictionary firstNodeDict = [[nodes objectAtIndex: 0] objectForKey: #"node"];

Dictionary object won't predicate

I have a json object coming in as
{
"c_id": "261",
"customer_id": "178729",
"name": "Three, Test"
},
{
"c_id": "261",
"customer_id": "178727",
"name": "Two, Test"
},
{
"c_id": "261",
"customer_id": "178728",
"name": "Two, Test"
},
{
"c_id": "261",
"customer_id": "185186",
"name": "Valid, Another"
},
{
"c_id": "261",
"customer_id": "183889",
"name": "White, Betty"
}
However when this code processes
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSMutableArray *tempCustomers = [[NSMutableArray alloc] init];
for (NSDictionary *dict in [json objectForKey:#"data"]) {
NSLog(#"dict: %#", dict);
NSLog(#"name: %#", [dict objectForKey:#"name"]);
[tempCustomers addObject:dict];
}
self.customers = tempCustomers;
NSLog(#"Customers: %#",customers);
self.customerData = [self partitionObjects:[self customers] collationStringSelector:#selector(self)];
NSLog(#"CustomerData: %#",customerData);
-(NSArray *)partitionObjects:(NSArray *)array collationStringSelector:(SEL)selector
{
UILocalizedIndexedCollation *collation = [UILocalizedIndexedCollation currentCollation];
NSInteger sectionCount = [[collation sectionTitles] count];
NSMutableArray *unsortedSections = [NSMutableArray arrayWithCapacity:sectionCount];
for (int i = 0; i < sectionCount; i++) {
[unsortedSections addObject:[NSMutableArray array]];
}
for (id object in array) {
NSInteger index = [collation sectionForObject:[object objectForKey:#"name"] collationStringSelector:selector];
[[unsortedSections objectAtIndex:index] addObject:object];
}
NSMutableArray *sections = [NSMutableArray arrayWithCapacity:sectionCount];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
for (NSMutableArray *section in unsortedSections) {
NSArray *sortedArray = [section sortedArrayUsingDescriptors:sortDescriptors];
//NSLog(#"Sort: %#",sortedArray);
//[sections addObject:[collation sortedArrayFromArray:section collationStringSelector:selector]];
[sections addObject:sortedArray];
}
return sections;
}
- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
NSLog(#"Search Display Controller: %#", self.customerData);
//NSString *predicateString = [NSString stringWithFormat:#"name CONTAINS[cd] '%#'",searchString];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"name CONTAINS[cd] '%#'",searchString];
self.filteredCustomers = [[self.customerData filteredArrayUsingPredicate:predicate] mutableCopy];
NSLog(#"Filtered Customers %#", self.filteredCustomers);
return YES;
}
It shows
2012-03-26 14:15:21.885 MyApp[65799:15003] name: Two, Test
2012-03-26 14:15:21.885 MyApp[65799:15003] dict: {
"c_id" = 261;
"customer_id" = 178728;
name = "Two, Test";
}
2012-03-26 14:15:21.885 MyApp[65799:15003] name: Two, Test
2012-03-26 14:15:21.885 MyApp[65799:15003] dict: {
"c_id" = 261;
"customer_id" = 185186;
name = "Valid, Another";
}
2012-03-26 14:15:21.885 MyApp[65799:15003] name: Valid, Another
2012-03-26 14:15:21.886 MyApp[65799:15003] dict: {
"c_id" = 261;
"customer_id" = 183889;
name = "White, Betty";
}
2012-03-26 14:15:21.886 MyApp[65799:15003] name: White, Betty
2012-03-27 08:35:24.764 MyApp[67330:fb03] Search Display Controller: (
(
),
(
{
"c_id" = 261;
"customer_id" = 178664;
name = "Test, My";
},
{
"c_id" = 261;
"customer_id" = 185182;
name = "Test, valid";
},
{
"c_id" = 261;
"customer_id" = 178729;
name = "Three, Test";
},
{
"c_id" = 261;
"customer_id" = 178727;
name = "Two, Test";
},
{
"c_id" = 261;
"customer_id" = 178728;
name = "Two, Test";
}
),
(
),
(
{
"c_id" = 261;
"customer_id" = 185186;
name = "Valid, Another";
}
),
(
{
"c_id" = 261;
"customer_id" = 183889;
name = "White, Betty";
}
),
(
),
(
),
(
),
(
)
)
2012-03-27 08:35:24.766 MyApp[67330:fb03] Filtered Customers (
)
Notice the " " around the name key are missing. I believe this is why my NSPredicate in my searchDisplayController isn't working. Why are the quotes being removed and how would I fix my searchDisplayController to work?
I just noticed, in your predicate, you have single quotes around the %# -- they shouldn't be there. Putting the single quotes around %# turns it into a literal.

How to convert data to JSON format, using SBJSON iPhone SDK?

I want to convert the given data to JSON format ... please help me to overcome this problem. Thanks in advance.
{
data = (
{
id = 1307983297;
name = "Aafaaq Mehdi";
},
{
id = 1350886273;
name = "Shah Asad";
},
{
id = 1636300537;
name = "Imran Baig";
},
{
id = 1640049813;
name = "Vinod Gowda";
}
);
}
UPDATE:
NSDictionary *dict = [[NSDictionary alloc] initWithDictionary:appDelegate.friendList];
results= (NSArray *)[dict valueForKey:#"data"];
NSMutableArray *arr = [[NSMutableArray alloc] init];
// loop over all the results objects and print their names
int ndx;
for (ndx = 0; ndx < results.count; ndx++)
{
[arr addObject:(NSDictionary *)[results objectAtIndex:ndx]];
}
FriendListModel *obj;
for (int x=0; x<[arr count]; x++)
{
obj = [[[FriendListModel alloc] initWithjsonResultDictionary:[arr objectAtIndex:x]] autorelease];
[arr replaceObjectAtIndex:x withObject:obj];
NSMutableArray *facebookJSON = [[[NSMutableArray alloc] init] autorelease];
for (obj in arr) {
NSDictionary *syedDict = [NSDictionary dictionaryWithObjectsAndKeys:obj.friendId,#"id", obj.friendName, #"name", nil];
NSString *facebookJSONFormat = [syedDict JSONRepresentation];
[facebookJSON addObject:facebookJSONFormat];
}
NSString *myArrayString = [facebookJSON description];
NSString *braceInArr = [NSString stringWithFormat:#"[%#]", myArrayString];
[self setFormDataRequest:[ASIFormDataRequest requestWithURL:url]];
[formDataRequest setDelegate:self];
[formDataRequest setPostValue:braceInArr forKey:#"friend_list"];
[formDataRequest setDidFailSelector:#selector(uploadFailed:)];
[formDataRequest setDidFinishSelector:#selector(uploadFinished:)];
[formDataRequest startAsynchronous];
I got the output in this format:-
[(
"{\"id\":\"1307983297\",\"name\":\"No Man\"}",
"{\"id\":\"1350886273\",\"name\":\"Shah Asad\"}",
"{\"id\":\"1636300537\",\"name\":\"Imran Baig\"}",
"{\"id\":\"1640049813\",\"name\":\"Vinod Gowda\"}"
)]
{
"data":[
{
"id": 1307983297,
"name": "Aafaaq Mehdi"
},
{
"id": 1350886273,
"name": "Shah Asad"
},
{
"id": 1636300537,
"name": "Imran Baig"
},
{
"id": 1640049813,
"name": "Vinod Gowda"
}
]
}
That's your dad in JSON format... as for converting it, do you have a parser for the original format?