使用JSON-Framework for Objective-C解析嵌套JSON对象 [英] Parsing nested JSON objects with JSON Framework for Objective-C

查看:103
本文介绍了使用JSON-Framework for Objective-C解析嵌套JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下JSON对象:

I have the following JSON object:

{
"response": {
    "status": 200
},
"messages": [
    {
        "message": {
            "user": "value"
            "pass": "value",
            "url": "value"
         }
 ]
    }

}

我使用JSON-Framework(也尝试过JSON Touch)来解析并创建一个字典。我想访问消息块,并拉出用户,通过和url值。

I am using JSON-Framework (also tried JSON Touch) to parse through this and create a dictionary. I want to access the "message" block and pull out the "user", "pass" and "url" values.

在Obj-C中,我有以下代码:

In Obj-C I have the following code:

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

// Prepare URL request to download statuses from Twitter
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:myURL]]; 

// 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];

//Print contents of json-string
NSArray *statuses = [parser objectWithString:json_string error:nil];
NSLog(@"Array Contents: %@", [statuses valueForKey:@"messages"]);
NSLog(@"Array Count: %d", [statuses count]);


NSDictionary *results = [json_string JSONValue];
NSArray *tweets = [[results objectForKey:@"messages"] objectForKey:@"message"];

for (NSDictionary *tweet in tweets)
{
    NSString *url = [tweet objectForKey:@"url"];
    NSLog(@"url is: %@",url);
}



我可以拉出消息并查看所有消息 ,但我无法解析更深,并拉出用户,传递和url。

I can pull out "messages" and see all of the "message" blocks, but I am unable to parse deeper and pull out the "user", "pass", and "url".

推荐答案

解决:

NSArray *tweets = [[results objectForKey:@"messages"] valueForKey:@"message"];

这篇关于使用JSON-Framework for Objective-C解析嵌套JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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