JSON 写入中的顶级类型无效

Invalid top-level type in JSON write

我正在尝试创建一个简单的 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];

例外是

Invalid top-level type in JSON write

我也检查了 JSONdic 并且在所有情况下都不是零。 有什么建议吗?

我不能说是什么错误,因为我在这里试过并且成功了。

我尝试了 NSString *vCard = nilNSString *vCard = @"SOMESTRING",这两种情况都有效。

NSString *vCard = @"SOMESTRING"; // this is just a string, could be nil
    NSDictionary *JSONdic = nil;
    if (vCard) {
        JSONdic = @{@"status" : @"1", @"data" : vCard};
    } else {
        JSONdic = @{@"status" : @"0", @"error" : @"vCard is empty"};
    }
    NSError *error = nil;
    NSData *JSONData = [NSData data];

if ([NSJSONSerialization isValidJSONObject:JSONdic]) {
    JSONData = [NSJSONSerialization dataWithJSONObject:JSONdic options:NSJSONWritingPrettyPrinted error:&error];
}

确保 [BRContacts getContacts] 返回 NSString,我只是将 NSDictionary 声明重写为现代语法。

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

return [GCDWebServerDataResponse responseWithJSONObject:JSONdata];

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

return [GCDWebServerDataResponse responseWithJSONObject:JSONdic]; 

根据documentation对于类似问题一定要遵循这个规则:

An object that may be converted to JSON must have the following properties:

  • The top level object is an NSArray or NSDictionary.
  • All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
  • All dictionary keys are instances of NSString.
  • Numbers are not NaN or infinity.

Swift 4: 值得考虑

JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject]

而不是

JSONSerialization.data(withJSONObject: data, options: []) as? [String:AnyObject]