how to get objects from a json array in iphone?

守給你的承諾、 提交于 2019-12-08 03:51:08

问题


I am working on an iPhone app which involves using json-framework.I am getting array using NSURL

[{"firstName":"X","lastName":"Y","id":1},{"firstName":"A","lastName":"B","id":2}]

How can i get these 2 objects as like if i query for id=1, the O/P is

id=1
firstName:X
lastName:Y

and putting it in a table. I am googling the stuff from many days but didn't get any solution. Please help me out , explanation through code is appreciated.

Thank You.


回答1:


If your target SDK is ios4 or higher, you can use this project

https://github.com/stig/json-framework/

Once you add the source to your project, just

#import "SBJson.h"

and convert your Json string as follows

jsonResponse = [string JSONValue];

The method will fail if you don't have the full Json array in your string, but you can keep appending strings until it doesn't fail

To follow up for codejunkie's request below you can assume in your data structure that the jsonResponse is an NSArray In other implementations take care to test the response for NSArray or NSDictionary

NSArray * myPeople = [string JSONValue]; 
NSMutableDictionary * organizedData = [[NSMutableDictionary alloc] init];
for (NSDictionary * p in myPeople) {
    [organizedData setValue:p forKey:[p valueForKey:@"id"]];
}
    // now you can query for an id like so
    // [organizedData valueForKey:@"1"]; and your output will be what you wanted from the original question
    // just don't forget to release organizedData when you are done with it



回答2:


https://github.com/johnezang/JSONKit

I use this to get data from a webservice that spits out 50 records each having another 20 internal elements similar to the one you specify...

I use the JSONKit in the following manner..(Had a look at SBJson a lot of user but i got confused from the word go.)

JSONDecoder *jArray = [[JSONDecoder alloc]init];
NSMutableArray *theObject = [[NSMutableArray alloc] init];   
 theObject = [jArray objectWithData:theResponseData];//objectWithString:theResponseString
NSMutableArray *csArray = [[NSMutableArray array] retain] ;

    for(id key in theObject)
    {
      if([key valueForKey:@"firstName"]  != Nil) 
      {
       ........
       }
     if([key valueForKey:@"lastName"]  != Nil) 
      {
       ........
       }
    }

check it out and let me know if it works or not.. By the way Great responses guys... Good



来源:https://stackoverflow.com/questions/7958992/how-to-get-objects-from-a-json-array-in-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!