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.
Related
{
"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];
}
}
}
}
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"];
}
I want my NSArray sampleData to receive actual data from parse.com database assuming like this:
self.sampleData = #[ #{ #"date": #"12/5/2014",
#"group": #[ #{ #"text": #"post1", #"location": #"x,y" },
#{ #"text": #"post2", #"location": #"x,y" },
#{ #"text": #"post3", #"location": #"x,y" },
#{ #"text": #"post4", #"location": #"x,y" },
#{ #"text": #"post5", #"location": #"x,y" }
]
},
#{ #"date": #"12/3/2014",
#"group": #[ #{ #"text": #"post6", #"location": #"x,y" },
#{ #"text": #"post7", #"location": #"x,y" },
#{ #"text": #"post8", #"location": #"x,y" },
#{ #"text": #"post9", #"location": #"x,y" },
#{ #"text": #"post10", #"location": #"x,y" }
]
}
];
As you can see, I want to group text and location by date, so that I can display them in a view with date as header and text/location as content.
Here below is what I'm capable doing so far:
PFQuery *postQuery = [PFQuery queryWithClassName:kPAWParsePostsClassKey];
[postQuery whereKey:kPAWParseUserKey equalTo:[PFUser currentUser]];
postQuery.cachePolicy = kPFCachePolicyNetworkElseCache;
postQuery.limit = 20;
[postQuery findObjectsInBackgroundWithBlock:^(NSArray *myPosts, NSError *error)
{
if( !error )
{
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM/dd/yyyy"];
NSMutableArray *objectArray = [NSMutableArray new];
for (PFObject *object in myPosts) {
[objectArray addObject:#{#"createdAt": [formatter stringFromDate:object.createdAt], #"text": [object objectForKey:#"text"], #"location": [object objectForKey:#"location"]}];
}
self.sampleData = objectArray;
NSLog(#"My sampleData --> %#", self.sampleData);
}
}
];
The above code is obvious there's no grouping whatsoever, so really need help here.
Okay, so you have an array of items, and you want to group them into sections based on a particular key.
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM/dd/yyyy"];
// Sparse dictionary, containing keys for "days with posts"
NSMutableDictionary *daysWithPosts = [NSMutableDictionary dictionary];
[myPosts enumerateObjectsUsingBlock:^(PFObject *object, NSUInteger idx, BOOL *stop) {
NSString *dateString = [formatter stringFromDate:[object createdAt]];
// Check to see if we have a day already.
NSMutableArray *posts = [daysWithPosts objectForKey: dateString];
// If not, create it
if (posts == nil || (id)posts == [NSNull null])
{
posts = [NSMutableArray arrayWithCapacity:1];
[daysWithPosts setObject:posts forKey: dateString];
}
// add post to day
[posts addObject:obj];
}];
// Sort Dictionary Keys by Date
NSArray *unsortedSectionTitles = [daysWithPosts allKeys];
NSArray *sortedSectionTitles = [unsortedSectionTitles sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
NSDate *date1 = [formatter dateFromString:obj1];
NSDate *date2 = [formatter dateFromString:obj2];
return [date2 compare:date1];
}];
NSMutableArray *sortedData = [NSMutableArray arrayWithCapacity:sortedSectionTitles.count];
// Put Data into correct format:
[sortedSectionTitles enumerateObjectsUsingBlock:^(NSString *dateString, NSUInteger idx, BOOL *stop) {
NSArray *group = daysWithPosts[dateString];
NSDictionary *dictionary = #{ #"date":dateString,
#"group":group };
[sortedData addObject:dictionary];
}];
self.sampleData = sortedData;
This code will not generate exactly what you asked for. It will generate something that looks like this:
sampleData = #[ #{ #"date": #"12/5/2014",
#"group": ##[ PFObject*,
PFObject*,
PFObject*,
PFObject*,
PFObject*,
]
},
#{ #"date": #"12/3/2014",
#"group": #[ PFObject*,
PFObject*,
PFObject*,
PFObject*,
PFObject
]
}
];
There's no need to convert your PFObject* in the myPosts array into #{ #"text": #"post5", #"location": #"x,y" } since you'll lose access to other pieces of information. Here is how you would use this sampleData array.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView; {
return self.sampleData.count;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section; {
return self.sampleData[section][#"date"];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section; {
return self.sampleData[section][#"group"].count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath; {
PFObject *post = self.sampleData[indexPath.section][#"group"][indexPath.row];
UITableViewCell *cell = // dequeue A reusable tableviewcell here
// configure the cell here
return cell;
}
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];
}
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?