iphone - 如何在 Objective C 中解析 JSON 格式

标签 iphone objective-c ios json

大家好,我正在编写一个 iphone 应用程序,以便将谷歌搜索结果放入我的应用程序,我已经使用 JSON 类来获取结果......当我在 JSON Parser 中解析它并将其存储在 NSDictionary 中时,我得到了3 个键:

  1. 响应数据
  2. 回复详情
  3. 响应状态

重要的是第一个有搜索结果的responseData ...

问题是(我认为)responseData 中的另一个键是“results”,它包含 url 和其他东西,这是我的应用程序最重要的部分......如何访问它并将其放入 NSDictionary .....

这是请求:

http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=Paris%20Hilton

为了清楚起见,请考虑将该请求放入您的浏览器,当您获得结果时,将其复制并放入本网站的左侧,以查看 key 和其他内容:

http://json.parser.online.fr/

谢谢

最佳答案

你可以使用 JSON parser - SB Json将 json 字符串转换为 ObjectiveC 对象。请注意,ObjectiveC 中有许多可用的 JSON 解析器,但我选择 SB Json 是因为它易于使用。但根据一些基准测试,JSONKit 比 SBJson 更快。

一旦你有了你的 json 字符串,就可以像这样使用它 -

#import "JSON.h"

// Create SBJSON object to parse JSON
SBJSON *parser = [[SBJSON alloc] init];

// parse the JSON string into an object - assuming json_string is a NSString of JSON data
NSDictionary *object = [parser objectWithString:json_string error:nil];
NSLog(@"JSON data: %@", object);

如果您需要将来自 Twitter 的公共(public)时间线解析为 JSON,您将执行以下操作。同样的逻辑可以应用于您的 Google 搜索结果。您需要仔细检查您的 json 结构,这就是...

// Create new SBJSON parser object
SBJSON *parser = [[SBJSON alloc] init];

// Prepare URL request to download statuses from Twitter
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://twitter.com/statuses/public_timeline.json"]];

// Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];

// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil];

// Each element in statuses is a single status
// represented as a NSDictionary
for (NSDictionary *status in statuses)
{
  // You can retrieve individual values using objectForKey on the status NSDictionary
  // This will print the tweet and username to the console
  NSLog(@"%@ - %@", [status objectForKey:@"text"], [[status objectForKey:@"user"] objectForKey:@"screen_name"]);
}

关于iphone - 如何在 Objective C 中解析 JSON 格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7638629/

相关文章:

ios - 使用 CollectionView 和 CollectionViewCells 创建 Swift iOS 9 自定义键盘

ios - 如何将第一个值设置为表格颜色

iphone - 处理 UINavigationBar 后面的触摸

ios - 如何在Facebook分享弹出窗口中显示视频缩略图

iphone - UITableView注册Nib :forCellReuseIdentifier:

iphone - 在 UIPageViewController 中禁用/启用滚动

iphone - 有什么方法可以解决 'com.apple.product-type.framework' 问题吗?

ios - NSComparisonResult OrderedDescending 和 OrderedAscending 未按预期运行

ios - 在 Jenkins 上使用 faSTLane 构建失败失败

iphone - 如何在UILocalNotification中播放录制的声音