Parse json response in object c from http get request - objective-c

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.

Related

Recup specific ID from Json answer from api (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"];

[__NSCFString count]: Unrecognized selector

I know this has been asked before, but there is no answer that I have found useful.
First off here is my code
// load the .csv file with all information about the track
NSError *error;
NSString *filepath = [[NSBundle mainBundle] pathForResource:#"file" ofType:#"csv" inDirectory:nil];
NSString *datastring1 = [NSString stringWithContentsOfFile:filepath encoding:NSUTF8StringEncoding error:&error];
NSArray *datarow = [datastring1 componentsSeparatedByString:#"\r"];
//fill arrays with the values from .csv file
NSArray *data_seg = [datarow objectAtIndex:0]; //segment number
NSArray *data_slength = [datarow objectAtIndex:1]; //strait length
NSArray *data_slope = [datarow objectAtIndex:2]; //slope
NSArray *data_cradius = [datarow objectAtIndex:3]; //circle radius
NSArray *data_cangle = [datarow objectAtIndex:4]; //circle angle
NSLog(#"%i", [data_seg count]);
Okay, so there is the code, and I read that is has something to do with autorelease, but I was not able to add a retain like NSArray *data_seg = [[datarow objectAtIndex:0] retain]
When I run the code, I get [__NSCFString count]: unrecognized selector sent to instance 0x9d1ad50
Any help is appreciated, I'm not good at programming, and I am very new.
componentsSeparatedByString method returns an NSArray of NSString. Every item that you extract from datarow array is an NSString and an NSString doesn't respond to 'count'. Your code starting at //fill arrays is incorrect. Every objectAtIndex call will return an NSString*.
This is another way of saying that the datatype for data_seg is NSString* (not NSArray*).
With the corrected code snippet, the problem is because data_seg is a string, and -count is not a method of NSString. It seems you think data_seg is an NSArray.
Look at the documentation for -[NSString componentsSeparatedByString:] and see what it returns -- strings! So you get back an array of strings. So what you want is:
NSString *data_seg = [datarow objectAtIndex:0]; //segment number
NSLog(#"my segment number is: %#", data_seg);

Pulling Data From JSON

I have a simple JSON string that looks like
(
{
ID = 1;
response = Yes;
}
)
And my NSDictionary is not pulling the objectForKey. The jsonArray is displaying correctly. My code:
hostStr = [[hostStr stringByAppendingString:post] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *hostURL = [NSURL URLWithString:hostStr];
NSString *jsonString = [[NSString alloc] initWithContentsOfURL:hostURL];
self.jsonArray = [jsonString JSONValue];
[jsonString release];
NSLog(#"%#", jsonArray);
NSDictionary *infoDictionary = [self.jsonArray objectForKey:#"ID"];
NSLog(infoDictionary);
This is probably the case since you have completely invalid JSON (test it out at http://jsonlint.com/). Because you are missing the quotation marks in your JSON the elements won't match the id ID. All object names/keys need to be in quotation marks.
You're lucky that your framework interprets your invalid JSON (somehow) correctly so that you actually get an array or a dictionary. Because of this the result of NSLog will be correct.
Rewrite your JSON like this to get it working:
{
"ID": 1,
"response": "YES"
}
(Also be sure that jsonArray is a NSDictionary)

Parsed TouchXML XML file crashes when reading NSString

I'm able to successfully parse the contents of a XML file using TouchXML, but when I try to read an individual NSString, from the NSMutableArray that stores the parsed content, the iPhone app crashes.
My NSLog shows me that the file has been parse as it should, giving this output:
(
{
href = "mms://a19349.l412964549958.c41245496.f.lm.akamaistream.net/D/194359/4125596/v0001/reflector:49944";
},
{
href = "mms://a4322.l4129624350471.c414645296.a.lm.akamaistream.net/D/473432/4129566/v0001/reflector:546441";
} )
Here is the code I'm using to do the parsing:
NSMutableArray *res = [[NSMutableArray alloc] init];
.... Parsing happens here ....
Then I try to retrieve the string from the NSMutableArray, using this code (and the app crashes when trying to read this line of code, posted below NSMutableString *string1 = [NSMutableString stringWithString:url];
NSString *url = [[NSString alloc] init];
url = [res objectAtIndex:0];
NSMutableString *string1 = [NSMutableString stringWithString:url];
[string1 deleteCharactersInRange: [string1 rangeOfString: #"href = "]];
[string1 deleteCharactersInRange: [string1 rangeOfString: #";"]];
NSLog(#"Clean URL: %#", string1);
Please, how can I solve this problem? Thank you!
TouchXML returns you an array of NSDictionaries. In order to extract string you need to take value from this NSDictionary:
NSString *url = [[res objectAtIndex:0] objectForKey:#"href"];

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"];