如何从iPhone中的json数组获取对象? [英] how to get objects from a json array in iphone?

查看:68
本文介绍了如何从iPhone中的json数组获取对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个涉及使用json-framework的iPhone应用程序.我正在使用NSURL获取数组

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}]

如何获取这2个对象,就像我查询id = 1时,O/P为

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.

谢谢.

推荐答案

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

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"

并按如下所示转换您的Json字符串

and convert your Json string as follows

jsonResponse = [string JSONValue];

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

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

按照下面的代码管理员的要求进行跟进 您可以在数据结构中假设jsonResponseNSArray 在其他实现中,请小心测试对NSArray或NSDictionary的响应

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

这篇关于如何从iPhone中的json数组获取对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆