如何从iPhone的JSON数组中获取对象?
我正在研究一个涉及使用json-framework的iPhone应用程序。我正在使用NSURL获取数组
[{"firstName":"X","lastName":"Y","id":1},{"firstName":"A","lastName":"B","id":2}]
我如何得到这两个对象,如果我查询ID = 1,O / P是
id=1 firstName:X lastName:Y
放在桌子上 我从谷歌search多天,但没有得到任何解决scheme。 请帮助我,通过代码解释表示赞赏。
谢谢。
如果您的目标SDK是ios4或更高版本,则可以使用此项目
https://github.com/stig/json-framework/
一旦你将源代码添加到你的项目中,
#import "SBJson.h"
并按如下方式转换您的Jsonstring
jsonResponse = [string JSONValue];
如果你的string中没有完整的Json数组,那么这个方法会失败,但是你可以继续附加string直到不失败
为了跟上codejunkie的请求,你可以假设在你的数据结构中, jsonResponse
是一个NSArray
在其他实现中,注意testingNSArray或者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
https://github.com/johnezang/JSONKit
我用这个从Web服务获取数据,吐出50个logging,每个logging都有另外20个类似于你指定的内部元素。
我用下面的方式使用JSONKit ..(看看SBJson有很多用户,但是我对这个词很困惑。)
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) { ........ } }
检查出来,让我知道,如果它的工作与否。顺便说一句,伟大的回应家伙…好