繁体   English   中英

如何从iphone中的json数组中获取对象?

[英]how to get objects from a json array in iphone?

我正在开发一个涉及使用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

并把它放在一张桌子里。 我从很多天谷歌搜索的东西,但没有得到任何解决方案。 请帮助我,通过代码解释表示赞赏。

谢谢。

如果目标SDK是ios4或更高版本,则可以使用此项目

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

将源添加到项目后,只需

#import "SBJson.h"

并转换您的Json字符串如下

jsonResponse = [string JSONValue];

如果您的字符串中没有完整的Json数组,该方法将失败,但您可以继续追加字符串,直到它没有失败

要跟进下面的codejunkie请求,您可以在数据结构中假设jsonResponseNSArray在其他实现中,请注意测试NSArray或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

我用这个来从webservice获取数据,这些数据吐出50条记录,每条记录有20个内部元素,类似于你指定的内容...

我以下面的方式使用JSONKit ..(看了很多用户的SBJson但是我对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) 
      {
       ........
       }
    }

检查一下,让我知道它是否有效..顺便说一句,很棒的回答...好

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM