0

我尝试在 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 总是打印出空值

4

2 回答 2

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"];
于 2012-10-28T20:13:39.160 回答
0

检查 Web 浏览器中的 URL,您的 URL 不是正确的 JSON。

JSON验证链接:JSON验证

于 2012-10-28T17:46:58.573 回答