JSON 写入中的顶级类型无效

Mas*_*eni 7 json objective-c ios nsjsonserialization gcdwebserver

我正在尝试创建一个简单的 JSON 对象,但仍然出现错误,我知道我的代码有什么问题:

NSString *vCard = [BRContacts getContacts]; // this is just a string, could be nil
NSDictionary *JSONdic = nil;
if (vCard)
{
    JSONdic = [NSDictionary dictionaryWithObjectsAndKeys:@"1",@"status",vCard,@"data", nil];
}
else
{
    JSONdic = [NSDictionary dictionaryWithObjectsAndKeys:@"0",@"status",@"vCard is empty",@"error", nil];
}
NSError *error = nil;
NSData *JSONData = [NSJSONSerialization dataWithJSONObject:JSONdic options:NSJSONWritingPrettyPrinted error:&error];
return [GCDWebServerDataResponse responseWithJSONObject:JSONdata];
Run Code Online (Sandbox Code Playgroud)

例外是

JSON 写入中的顶级类型无效

我也检查过JSONdic,在每种情况下都不是零。有什么建议?

Mas*_*eni 4

好吧,我解决了。这是与此行相关的问题:

return [GCDWebServerDataResponse responseWithJSONObject:JSONdata];
Run Code Online (Sandbox Code Playgroud)

GCDWebServer的响应不需要 JSON,NSData而是一个NSDictionary:错误只是因为responseWithJSONObject处理输入以创建 JSON 对象(并且我传递了一个 JSON“预处理”对象)。所以我的错误与我的初始代码无关,所以我现在更新了它以供将来参考,我使用以下方法解决了:

return [GCDWebServerDataResponse responseWithJSONObject:JSONdic]; 
Run Code Online (Sandbox Code Playgroud)

根据类似问题的文档,请务必遵循以下规则:

可以转换为 JSON 的对象必须具有以下属性:

  • 顶级对象是 NSArray 或 NSDictionary。
  • 所有对象都是 NSString、NSNumber、NSArray、NSDictionary 或 NSNull 的实例。
  • 所有字典键都是 NSString 的实例。
  • 数字不是 NaN 或无穷大。