Problem with parsing JSON result - objective-c

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

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.

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

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