Question

i'm new in the iphone and json world . i have this json structure . You can see it clearly by putting it here http://jsonviewer.stack.hu/ .

 {"@uri":"http://localhost:8080/RESTful/resources/prom/","promotion":[{"@uri":"http://localhost:8080/RESTful/resources/prom/1/","descrip":"description
 here","keyid":"1","name":"The first
 name bla bla
 ","url":"http://localhost/10.png"},{"@uri":"http://localhost:8080/RESTful/resources/promo/2/","descrip":"description
here","keyid":"2","name":"hello","url":"http://localhost/11.png"}]}

i want to parse it with json-framework . I tried this

 NSDictionary *json    = [myJSON JSONValue];
            NSDictionary *promotionDic    = [json objectForKey:@"promotion"];
            NSLog(@" res %@ : ",[promotionDic objectAtIndex:0]); 

But then how to do to get for exemple , the name of the object at index 0 ? I think i should put object in an NSArray ? but i dont find how :/ and i dont the number of object is variable . Help please .

Was it helpful?

Solution

The JSON says:

..."promotion":[{"@u...

That "[" there means that "promotion" is keyed to an array, not a dictionary.

So really your code should be:

NSDictionary *json    = [myJSON JSONValue];
NSArray *promotions   = [json objectForKey:@"promotion"];
NSLog(@"res: %@",[promotions objectAtIndex:0]); 

OTHER TIPS

First off, You need this line after you load the JSON

        NSLog(@" json %@ : ",[json description]); 

That will tell you what you have.

Secondly, you can't call objectAtIndex: on a dictionary. If it works, its because promotionDict is really an NSArray. (The NSLog will tell you). In Objective - C you can assign to any kind of pointer, which is confusing to new developers, but is part of the language, and really is a feature.

With an NSArray you can ask for the number of things in it, [myArray count], etc. You need to command double click in XCode to open up the docs for NSDictionary, etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top