无法在IOS 5上使用Json解析数据

时间:2012-10-28 17:42:23

标签: iphone ios json

我尝试在ios 5上使用json获取一些数据但是我失败了...... 有人可以帮助我,并告诉我为什么它没有成功。 这是我的实现代码

定义:

#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1
#define kLatestKivaLoansURL [NSURL URLWithString:@"http://jaksport.com/jarray.php"] //2

然后在viewdidload中:

NSData* data = [NSData dataWithContentsOfURL:
                        kLatestKivaLoansURL];
        [self performSelectorOnMainThread:@selector(fetchedData:)
                               withObject:data waitUntilDone:YES];

这是功能:

- (void)fetchedData:(NSData *)responseData {
    //parse out the json data
    NSError* error;
    NSDictionary* json = [NSJSONSerialization
                          JSONObjectWithData:responseData //1
                                     options:kNilOptions
                                       error:&error];

    NSArray* key = [json objectForKey:@"price"]; //2

    NSLog(@"value: %@", key); //3


  }

这是json文件:

{
    "prices":
        {
        "price":[
            {
                "id":1,
                "name":"Rosie Gradas",
                "beer":4.5,
                "cider":4.5,
                "guinness":4
            },
            {
                "id":2,
                "name":"Wicked Wolf",
                "beer":5,
                "cider":4.5,
                "guinness":4
            },
            {
                "id":3,
                "name":"Cafe Posh",
                "beer":6,
                "cider":5.5,
                "guinness":5.5
            },
            {
                "id":4,
                "name":"My House",
                "beer":16,
                "cider":15.5,
                "guinness":15.5
            }
        ]
    }
}

nslog始终打印出空值

2 个答案:

答案 0 :(得分:2)

错误在于如何访问JSON中的对象:

{
  "prices":
    {
    "price":[
        {
            "id":1,
            "name":"Rosie Gradas",
            "beer":4.5,
            "cider":4.5,
            "guinness":4
        }
}

如果有这样的JSON来访问价格数组,你可以使用这样的语法

NSArray *price = [[json objectForKey:@"prices"]objecForkey:@"price"];

答案 1 :(得分:0)

检查网络浏览器中的网址,您的网址不是正确的JSON。

JSON验证链接:JSON Verification