如何在目标C/iOS中的客户端上创建虚拟JSON数据?

Dan*_*nny 10 json objective-c nsdictionary foundation ios

我想在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];
Run Code Online (Sandbox Code Playgroud)

尝试创建该JSON数据变量或尝试解析时,尝试更改(并尝试更改内容,例如将NSString*从该JSON字符串切换为NSData*)已经产生了null parsedJsonData数据或异常.

如何在我自己的代码中创建虚拟JSON数据,以便可以通过解析JSON数据的普通Foundation类来解析它?

Jam*_*s P 21

我会将我的测试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" 
     }]
}
Run Code Online (Sandbox Code Playgroud)

然后,为了在您的应用程序中解析此文件,您只需从bundle目录中加载该文件即可.

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);
Run Code Online (Sandbox Code Playgroud)

现在很容易扩展它以加载任意数量的响应,并且基本上具有本地Web服务.然后,将其调整为从远程服务器加载响应将不会有太多工作.