如何在客户端使用Objective C / iOS创建虚拟JSON数据?

11

我想为我的应用程序设置静态的JSON虚拟数据进行处理。这纯粹是客户端的;我不想从网络中检索任何内容。

到目前为止,我看到的所有问题和答案都是使用NSData*变量存储从网络调用中检索到的内容,并且[JSONSerialization JSONObjectWithData:...]通常对手动创建的数据进行操作。

以下是我在Xcode中尝试的示例。

NSString* jsonData = @" \"things\": [{ \
\"id\": \"someIdentifier12345\", \
\"name\": \"Danny\" \
\"questions\": [ \
    { \
        \"id\": \"questionId1\", \
        \"name\": \"Creating dummy JSON data by hand.\" \
    }, \
    { \
        \"id\": \"questionId2\", \
        \"name\": \"Why no workie?\"
    } \
    ], \
\"websiteWithCoolPeople\": \"http://stackoverflow.com\", \
}]}";

NSError *error;
NSDictionary *parsedJsonData = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];

尝试像更改从JSON字符串到NSData的NSString *那样的尝试,导致解析出null parsedJsonData数据或在创建JSON数据变量或尝试解析它时出现异常。

我该如何在我的代码中创建虚拟JSON数据,以便可以通过正常解析JSON数据的Foundation类进行解析?


1
我不相信JSON可以以字符串开头。尝试在“things”之前加上{。然后,使用[jsonData dataUsingEncoding:NSUTF8StringEncoding]方法获取你的字符串,因为NSJSONSerialization只接受数据,而不是字符串 :) - anon_dev1234
谢谢。我以前尝试过那种方法,但你揭示了我可能有格式不正确的JSON,这就是为什么我似乎无法手动创建数据的原因。你能否发一个小例子展示一下JSON应该如何看起来,这样我在尝试新的JSON时就可以测试一下它是否有效?如果有效,我会将你的答案标记为答案,因为试图做这件事的人很可能会遇到格式不正确的JSON问题。 - Danny
1
当我需要这样做时,我会在应用程序包中使用文本文件来包含JSON,而不是在代码中使用NSString。我认为这样可以更轻松地替换生产URL,并且格式化也应该更容易。 - James P
1
当您编写完字符串后,请添加一个NSLog来打印它,并将其复制/粘贴到类似于http://json.parser.online.fr/的网站上进行语法检查。 - Hot Licks
1
而且JSON语法非常简单。你可以在5分钟内掌握基础知识,并有时间去喝咖啡。 - Hot Licks
有第三方的JSON包,比如SBJSON,可以接受NSStrings。 - Hot Licks
6个回答

23

我会将我的测试JSON保存为应用程序中的单独文件。这样做的好处是,您可以只需从Web服务中复制并粘贴响应,而无需将它们转换为NSDictionaries或转义字符串即可轻松阅读。

我已经正确格式化了您的JSON(使用jsonlint),并将其保存到名为testData.json的文件中,该文件位于应用程序包中。

{"things":
    [{
     "id": "someIdentifier12345",
     "name": "Danny",
     "questions": [
                   {
                   "id": "questionId1",
                   "name": "Creating dummy JSON data by hand."
                   },
                   {
                   "id": "questionId2",
                   "name": "Why no workie?"
                   } 
                   ], 
     "websiteWithCoolPeople": "http://stackoverflow.com" 
     }]
}

那么,为了在您的应用程序中解析此文件,您只需从捆绑目录加载该文件即可。

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"testdata" ofType:@"json"];
NSData *jsonData = [[NSData alloc] initWithContentsOfFile:filePath];

NSError *error = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];

NSLog(@"%@", jsonDict);

现在很容易将这个扩展为加载任意数量的响应,从而实现本地网络服务。然后,适应从远程服务器加载响应也不会太费力。


喜欢那个外部文件的说明。回答很好! - Danny
@James P,我该如何创建JSON文件? - Bharat Modi
只需将您的JSON放入纯文本文件中,并将扩展名从.txt更改为.json。 - James P

4
尝试像这样的东西!
NSDictionary *jsonObject = @{@"id": @"someIdentifier",
                             @"name":@"Danny",
                             @"questions":@[
                                            @{@"id":@"questionId1",
                                              @"name":@"Creating dummy JSON"},
                                            @{@"id":@"questionId2",
                                              @"name":@"Creating dummy JSON"},
                                            @{@"id":@"questionId3",
                                              @"name":@"Creating dummy JSON"}],
                             @"websiteCoolPeople":@"http://stackoverflow.com"};


NSLog(@" JSON = %@",jsonObject); // let's see if is correct

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonObject options:NSJSONWritingPrettyPrinted error:nil];

NSLog(@" JSON DATA \n  %@",[NSString stringWithCString:[jsonData bytes] encoding:NSUTF8StringEncoding]);


//lets make a check

if ([NSJSONSerialization isValidJSONObject:jsonObject] == YES) {

    NSLog(@" ;) \n");
}
else{

    NSLog(@"Epic Fail! \n");

}


//Going back

NSDictionary *parsedJSONObject = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil];


NSLog(@"Cool! :  %@",parsedJSONObject);

我喜欢你的回答明确地用字典创建了JSON,并使用与我的原始问题相关的数据。这样,未来的搜索者将会觉得很容易跟进。 - Danny

2
首先,
-(void)createJsonData
{
    //your objects for json
    NSArray * objects=@[@"object1",@"object2",@"object3",@"object4"];
    //your keys for json
    NSArray * keys=@[@"key1",@"key2",@"key3",@"key4"];

    //create dictionary to convert json object
    NSDictionary * jsonData=[[NSMutableDictionary alloc] initWithObjects:objects forKeys:keys];


    //convert dictionary to json data
    NSData * json =[NSJSONSerialization dataWithJSONObject:jsonData options:NSJSONWritingPrettyPrinted error:nil];


    //convert json data to string for showing if you create it truely
    NSString * jsonString=[[NSString alloc] initWithData:json encoding:NSUTF8StringEncoding];

    NSLog(@"%@",jsonString);
}

这将创建一个jsonData。另一个事实是,要创建数据,您应该使用dataWithJSONObject方法。而此方法接受NSDictionary或NSArray。NSString类无效。


1
答案在于创建正确格式的JSON。如果手动创建的JSON格式不正确,则序列化时只会得到“null”值。下面是一些小因素,它们让我感到非常困惑,直到@bgoers提到其中之一。
  • 确保你包含了正确的大括号([{}])并适当地关闭它们。这其实不是一个小因素,但如果你基于文档来编写数据(就像我一样),那么你可能会忽略复制/粘贴其中一个花括号。
  • 在复制/粘贴JSON数据的外观时,请确保所有使用的字符,特别是“引号”,都是统一的。结果证明,我使用的是华丽的开放和关闭引号,它们被编码到文档中,而不是你在Xcode中输入的“引号”。

一旦你有了有效的JSON,Foundation类应该可以正常工作。


1
#import "SBJSON.h"

NSDictionary *dictionary = [[NSDictionary alloc] initWithObjects:[NSArray arrayWithObjects:
                                                                      @"2013-03-27",
                                                                      @"2013-04-04",
                                                                      @"2013-03-27",
                                                                      @"0",
                                                                      @"1",
                                                                      @"1",nil]
                                                             forKeys:[NSArray arrayWithObjects:
                                                                      @"startDate",
                                                                      @"endDate",
                                                                      @"selectedDate",
                                                                      @"shadowsOfID",
                                                                      @"appointmentsOfID",
                                                                      @"shadowType",nil]];


   SBJsonWriter *p = [[SBJsonWriter alloc] init];
        NSString *jsonStr = [NSString stringWithFormat:@"%@",[p stringWithObject:dictionary]];

jsonStr现在包含以下内容:
"{\"shadowType\":\"1\",\"startDate\":\"2013-03-27\",\"selectedDate\":\"2013-03-27\",\"endDate\":\"2013-04-04\",\"shadowsOfID\":\"0\",\"appointmentsOfID\":\"1\"}";

请注意:字典可以是项目中的plist文件。

0

请访问此链接以获取在线的JSON到NSDictionary/NSArray转换器:

https://erkanyildiz.me/lab/jsonhardcode/

使用格式良好的JSON作为输入,然后将结果复制并粘贴到您的代码中作为文字字面量NSDictionary *myDict = @{...};


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接