Recup specific ID from Json answer from api (objective-c) - objective-c

I have a specific username (NSString *) and I do a request to the api (via sendSynchronousRequest) to get all the users. The data collected have this pattern :
{"users":
[{"id":3,"username":"Max","email":"max#xxx.com","rank":0,"level":0,"score":{},"first_name":null,"last_name":null,"date_birth":null},
{"id":4,"username":"Guest","email":"ere#xxx.com","rank":0,"level":0,"score":{},"first_name":null,"last_name":null,"date_birth":null},
{"id":5,"username":"Root","email":"localhost#local.com","rank":0,"level":0,"score":{},"first_name":null,"last_name":null,"date_birth":null},
{"id":6,"username":"test_user","email":"test#test.fr","rank":0,"level":0,"score":{},"first_name":null,"last_name":null,"date_birth":null}
]}
and I'm interested in getting the id value for a specific username (like "4" for "Guest") to use it in other requests.
I tried to follow how to parse array of objects using json for iphone but got some problems due to the format {"xxx":[{...},{...},..]}
Any help will be appreciated. Thx for your time.

First parse the JSON string and put it into NSDictionary and extract the NSArray of users then use NSPredicate to get the user you want
NSDictionary *usersDictionary = [jsonString JSONValue];
NSArray *users = [usersDictionary valueForKey:#"users"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"username = %#", userName];
NSDictionary *user = [[users filterUsingPredicate:predicate] firstObject];
NSNumber *userId = [user objectForKey:#"id"];

Related

How to extract selected attribute(s) from an NSArray of Core Data entity objects and form into a joint string?

Normally, if I have an NSArray of just NSString's, I can use the NSArray's method:
- (NSString *)componentsJoinedByString:(NSString *)separator
to get a String (like "John,David,Peter"). However, if I have an NSArray of Core Data Entity objects and I just need to to get 1 attribute within (say, the "name" attribute only of each entity object), what is the easiest way to do this?
The Core Data entity object can have many attributes (name, phone, birthdate), but I just want a string like "John,David,Peter".
The following will do a fetch for only the name properties of the Person objects:
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"Person"];
request.propertiesToFetch = #[#"name"];
request.resultType = NSDictionaryResultType;
NSArray *array = [managedObjectContext executeFetchRequest:request error:nil];
NSString *names = [[array valueForKey:#"name"] componentsJoinedByString:#","];
NSLog(#"%#", names);
You need to set the resultType to NSDictionaryResultType otherwise it will ignore propertiesToFetch. The result from the fetch is an array of Dictionaries. Using valueForKey and componentsJoinedByString will create a single string out of all the names.
Your best option is the straightforward one of building up a NSMutableString by iterating over the items in you array and asking each one for its name to use in appendString:. You could add a description method to the entity object and then use the method you mentioned but description is used for other things and would probably cause conflicts.
// Assuming you have the list of entities - NSArray *entityObjects
NSMutableString *nameAttributes = [[NSMutableString alloc] init];
for(int i = 0; i < [entityObjects count]-1; i++){
[nameAttributes appendString:[NSString stringWithFormat:#"%#, ", [entityObjects objectAtIndex:i].name]];
}
[nameAttributes appendString:[NSString stringWithFormat:#"%#", [entityObjects lastObject].name]];
If you have an NSArray *objects of Core Data objects, each of which has a name attribute, then you can use
NSArray *names = [objects valueForKey:#"name"];
to get a new array with all the names, which you can then concatenate with
NSString *allNames = [names componentsJoinedByString:#","];
You can simply do like that,
NSString *toCollectString =#"";
for(int k =0;k<self.arrayHoldingObjects.count;k++)
{
ModelName *model = [self.arrayHoldingObjects objectAtIndex:k];
NSString *str = model.name;
toCollectString = [toCollectString stringByAppendingString:str];
}
You will get the names in toCollectString.

Parse json response in object c from http get request

i'm trying to parse the response i get from a http get request in object c, i have do this:
NSString *returnValue = [[NSString alloc] initWithData:oRespondeData encoding:NSUTF8StringEncoding];
SBJsonParser *jParser = [[SBJsonParser alloc] init];
NSDictionary *JSONresponse = [jParser objectWithString:returnValue];
then i search for a specific key:
NSArray *jSon1 = [JSONresponse objectForKey:#"links"];
and in the array there is only one element, and if i log it i have this:
NSLog(#"%#",[jSon1 objectAtIndex:0]);
log:
(
"Video.720p.X264-..",
"",
"http://video/dl/Video.720p.X264-.."
)
how i can get the url with http? i have tried everything, i have also tried to trim the string to delete the whitespaces, but seems that it's not a nsstring because i receive
[__NSArrayM stringByTrimmingCharactersInSet:]: unrecognized selector sent to instance
how i can do?
[jSon1 objectAtIndex:0]
is returning an array of 3 separate strings, so if yo'ure trying to get the 3rd string you could do:
NSArray *links = [jSon1 objectAtIndex:0];
NSString *httpUrl = [links objectAtindex:2];
Hopefully i understand your question correctly.

A reverse kind of string compare using NSPredicate

I've been searching for this answer all over internet but so far no luck. So I need to consult the smart and nice people here. This is my first time asking a question here, so I hope I am doing this right and not repeating the question.
For all the examples I saw, it's the search string that is a substring of what's stored in the Core Data. On the other hand, I want to achieve the following:
The strings stored in core data are actually sub-strings. I want to do a search by getting all core data rows that have substrings belong to the provided search string.
For ex:
In core data, I have "AB", "BC","ABC","ABCDEF","GH", "ABA"
And in the app I do a search by providing the super-string: "ABCDEF", the result will return "AB","BC","ABC","ABCDEF" but not "GH", "ABA" because these two sub-strings don't belong to the super-string.
How should I setup my predicateWithFormat statement?
This wont' work cuz it's doing the opposite:
NSPredicate *myPredicate = [NSPredicate predicateWithFormat:#"substring LIKE[c] %#", #"ABCDEF"];
Thanks all!
The reverse of CONTAINS will not work. Also, you will not be able to use LIKE because you would have to take the attribute you are searching and transform it into a wildcard string.
The way to go is to use MATCHES because you can use regular expressions. First, transform your search string into a regex by affixing a * after each letter. Then form the predicate.
This solution has been tested to work with your example.
NSString *string= #"ABCDEF";
NSMutableString *new = [NSMutableString string];
for (int i=0; i<string.length; i++) {
[new appendFormat:#"%c*", [string characterAtIndex:i]];
}
// new is now #"A*B*C*D*E*F*";
fetchRequest.predicate = [NSPredicate predicateWithFormat:
#"stringAttribute matches %#", new];
where stringAttribute in the predicate is the name of your NSString attribute of your managed object.
I think this will work:
NSPredicate *pred = [NSPredicate predicateWithFormat:#"%# contains self",#"ABCDEF"];
You would use it like this in core data:
-(IBAction)doFetch:(id)sender {
NSFetchRequest *request = [[NSFetchRequest alloc] init];
request.entity = [NSEntityDescription entityForName:#"Expense" inManagedObjectContext:self.managedObjectContext];
request.predicate = [NSPredicate predicateWithFormat:#"%# contains desc",#"ABCDEF"];
NSArray *answer = [self.managedObjectContext executeFetchRequest:request error:nil];
NSLog(#"%#",answer);
}
In this example, "desc" is an attribute of the entity "Expense". This correctly retrieves only the rows where "desc" is a substring of "ABCDEF".

How to convert a JSON array into an NSArray

I've been having trouble finding out how to convert a JSON array into an NSArray.
I have a php script that creates an array that is converted into JSON which is then sent and stored into an NSString that looks like:
[1,2,3,4]
My problem is that I need to make that into an NSArray of ints. How would one do that?
Thanks!
You should look at the documentation of the NSJSONSerialization class.
You can hand it the NSData received from a remote call that is a string in JSON format and receive the array or dictionary it contains.
NSObject *o =[NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
// other useful "options":
// 0
// NSJSONReadingMutableLeaves
// NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers
you should then check that o is of the type you expect for sanity purposes
If I wanted to quickly break that into an array I would do it like this:
NSString * jstring = #"[1,2,3,4]"; //your json string
jstring = [jstring stringByReplacingOccurrencesOfString:#"[" withString:#""];
jstring = [jstring stringByReplacingOccurrencesOfString:#"]" withString:#""];
NSArray * intArray = [string componentsSeparatedByString:#","];
//you could create your int from the array like this
int x = [[intArray objectAtIndex:0]intValue];
Import the SBJson in your project (drag and drop it)
#import "SBJson.h"
Then where you receive the JSON response from the php file
NSArray *array = [responseString JSONValue];

Problem with parsing JSON result

I have a problem with parsing a JSON result. This is what I get from my HTTP request:
{"subscriptions": [
{"id":"A", "title":"A title"},
{"id":"B", "title":"B title"},
]}
And this is what I'm doing in my code:
// Getting the result<br>
NSString *str = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
// Creating the JSON parser<br>
SBJSON *parser = [[SBJSON alloc] init];
// Parse result in an object<br>
NSDictionary *result = [parser objectWithString:str];
So far everything works fine. I have one key/value pair in my result object which I think is the subscriptions object. But the problem is now: How can I access the inner objects of it like the id and title?
Thanks for help.
The JSON parser will create nested NSArray and NSDictionary objects for you. To get to the array use:
NSArray *array = [result objectForKey:#"subscriptions"];
Then access the objects in the array like so:
NSDictionary *arrayObject = [array objectForIndex:0];
And finally, to get one of the inner objects do:
NSString *stringObject = [arrayObject objectForKey:#"id"];