开发者

How can I pull out nested JSON values in a collection in objective-C?

I've got an OData service that can return JSON values for a开发者_Go百科n object collection. I'd like to point an iPhone app at a collection of JSON objects off of that service (results shown below with one sample record).

How can I parse these nested values? When I convert the response string to JSON values, it only grabs "d" (my code for that is also below).

{
"d" : {
"results": [
{
"__metadata": {
"uri": "http://someserver/service.svc/collection(1234L)", "type": "My.Namespace.Type"
}, "Property1": "value1", "Property2": 7274, "Collection1": {
"__deferred": {
"Property3": "http://someserver/service.svc/collection(1234L)/Images"
}
}
},
...

Sample objective C code:

- (void)requestFinished:(ASIHTTPRequest *)request
{
    if (request.responseStatusCode == 200)
    {
        NSString *responseString = [request responseString];

        textView.text = responseString;

        NSDictionary *responseDict = [responseString JSONValue];
        NSArray *keys = [responseDict allKeys];

        [self printArray:keys]; // This prints "d"
        ...
     }
}


It seems that you have a root key "d" and all the keys are in fact subkeys, try

NSDictionary *responseDict = [[responseString JSONValue] objectForKey:@"d"];

or even

NSArray *responseArray = [[[responseString JSONValue] objectForKey:@"d"] objectForKey:@"results"];

it's an alternance of NSArray and NSDictionnary :

NSDictionary *responseDict = [[responseString JSONValue] valueForKey:@"d"];
NSArray *responseArray = [responseDict valueForKey:@"results"];

NSDictionary *dict;
for(int i=0; i< [responseArray count]; i++){
    dict = [responseArray objectAtIndex:i];
    NSLog(@"- %@",[responseArray objectAtIndex:i]);

}

it's always strongly dependant on your JSON generator. So I cannot tell you for sure it's always the best way of digging, but in this case it seems so. Just remember:

  • [data1,data2,data3,data4] -> array
  • {key1:data1,key2:data2} -> dictionary


From the looks of it, d is the key to another dictionary that contains they key results which contains an array with your data. Try using

NSLog(@"%@", responseDict);

to see the whole tree hierarchy.


You can use the json-framework to convert the json data to an NSDictionary.


use this url http://mobileorchard.com/tutorial-json-over-http-on-the-iphone/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜