【问题标题】:JSONKit - objectFromJSONData always seems to return nilJSONKit - objectFromJSONData 似乎总是返回 nil
【发布时间】:2013-01-15 06:01:23
【问题描述】:

我不敢相信我连这个简单的测试存根都无法使用 JSONKit...

我有一个包含有效 JSON 文档的 json 文件,以及这个简单的代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    NSError *err = nil;
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"dk" ofType:@"json"];
    NSData *jsonData = [NSData dataWithContentsOfFile:filePath options:NSDataReadingMappedIfSafe error:&err];

    NSString *dkk = [[NSString alloc] initWithContentsOfFile:filePath];
    NSLog(@"Found file with contents: \n%@",dkk);

    if(jsonData)
    {
        NSLog(@"Data length is: %d",[jsonData length]);
        id objectReturnedFromJSON = [jsonData objectFromJSONData];
        if(objectReturnedFromJSON)
        {
            if([objectReturnedFromJSON isKindOfClass:[NSDictionary class]])
            {
                NSDictionary * dictionaryFromJSON = (NSDictionary *)objectReturnedFromJSON;
                // ...
            } else {
                NSLog( @"no dictionary from the data returned by the server... check the data to see if it's valid JSON");
            }
        } else {
            NSLog( @"nothing valid returned from the server...");
        }
    } else {
        NSLog( @"no data back from the server");
    }

}

objectFromJSONData 的结果似乎总是返回 null。输出如下图:

2013-01-15 00:58:37.187 JSONTest[38110:c07] Found file with contents: 
myObject = {
    "first": "John",
    "last": "Doe",
    "age": 39,
    "sex": "M",
    "salary": 70000,
    "registered": true,
    "favorites": {
        "color": "Blue",
        "sport": "Soccer",
        "food": "Spaghetti"
    } 
}

2013-01-15 00:58:51.818 JSONTest[38110:c07] Data length is: 196
2013-01-15 00:58:54.058 JSONTest[38110:c07] Data length is: (null)
(lldb) 

我到底错过了什么?输入的 JSON 是有效的(如 NSLog 语句所示)。

对不起,如果这是一些愚蠢的事情,但即使是在这个小测试用例上,我也浪费了太多时间,让我觉得我错过了一些东西。

【问题讨论】:

  • 输入您的 JSON here 并验证它。 myOjbect 似乎不是您的 JSON 的一部分。

标签: ios objective-c jsonkit


【解决方案1】:

您拥有的 JSON 无效。它没有根元素,而且myObject 键也没有括在括号内。

【讨论】:

  • 好遗憾 - 我从在线 JSON 教程中获取了这个示例,因此认为它很好。感谢所有回复的人。今晚我会重试这个问题,如果这就是全部的话。
猜你喜欢
  • 2012-09-07
  • 2017-03-28
  • 2015-03-05
  • 2014-08-25
  • 2016-05-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多