如何使用JSON-FrameworkparsingiPhone SDK(XCode)中的JSON对象
我有这样的JSON对象:
{ "data": {"array": ["2", {"array": [ {"clientId":"1","clientName":"Andy","job":"developer"}, {"clientId":"2","clientName":"Peter","job":"carpenter"} ] } ] }, "message":"MSG0001:Success", "status":"OK" }
我想使用JSON-Framework获取数组[0]值(2)和数组[1]值(clientId,clientName,作业)。 你有什么想法如何做到这一点?
假设你已经按照指示将 JSON-Framework 安装到了你的项目中,下面是你如何使用它(摘自这里的文档 ):
// Parse the string into JSON NSDictionary *json = [myString JSONValue]; // Get the objects you want, eg output the second item's client id NSArray *items = [json valueForKeyPath:@"data.array"]; NSLog(@" client Id : %@", [[items objectAtIndex:1] objectForKey:@"clientId"]);
谢谢你的回答,我的问题解决了,我修改了一下你的代码,这里是:
// Parse the string into JSON NSDictionary *json = [myString JSONValue]; // Get all object NSArray *items = [json valueForKeyPath:@"data.array"]; NSArray *array1 = [[items objectAtIndex:1] objectForKey:@"array"]; NSEnumerator *enumerator = [array1 objectEnumerator]; NSDictionary* item; while (item = (NSDictionary*)[enumerator nextObject]) { NSLog(@"clientId = %@", [item objectForKey:@"clientId"]); NSLog(@"clientName = %@",[item objectForKey:@"clientName"]); NSLog(@"job = %@", [item objectForKey:@"job"]); }
我们需要1个类,比如MyData.h和MyData.m
//MyData.h @interface MyData : NSObject { NSString *clientId; NSString *clientName; NSString *job; } @property (nonatomic, retain) NSString *clientId; @property (nonatomic, retain) NSString *clientName; @property (nonatomic, retain) NSString *job; @end //MyData.m @implementation MyData @synthesize clientId, clientName, job; - (void)dealloc{ [clientId release]; [clientName release]; [job release]; [super dealloc]; } @end //-------------------------------------
要存储我们的数据:
NSMutableArray *dataArray = [[NSMutableArray alloc]init]; while (item = (NSDictionary*)[enumerator nextObject]) { MyData *aMyData = [[MyData alloc] init]; aMyData.clientId = [item objectForKey:@"clientId"]; aMyData.clientName = [item objectForKey:@"clientName"]; aMyData.job = [item objectForKey:@"job"]; [dataArray addObject:aMyData]; [aMyData release]; aMyData = nil; }
尝试这个
while (item = (NSDictionary*)[enumerator nextObject]) { NSMutableArray *myArray = [[NSMutableArray alloc] init]; [myArray AddObject:((NSDictionary*)[enumerator nextObject])]; }
您可以创build数据点的层次结构。 例如,如果要获取JSON对象的内部数组,可以使用以下命令访问它:
NSArrray *objectArray = jsonObject[@"array"][@"2"][@"array"];
或者,你可以做类似的事情。 例如,在Yelp API中,您提供了一个业务的JSON。 将这些业务放置在一个数组中,您可以通过执行以下操作来访问对象的不同元素:
NSString *businessLocation = [businessArray objectAtIndex: indexOfBusinessInArray][@"location"][@"display_address"];
如何将这个数据存储在NSMUtableArray?
while (item = (NSDictionary*)[enumerator nextObject]) { NSLog(@"clientId = %@", [item objectForKey:@"clientId"]);//this NSLog(@"clientName = %@",[item objectForKey:@"clientName"]);//this NSLog(@"job = %@", [item objectForKey:@"job"]);//this }