JSON写入中的无效顶级类型 [英] Invalid top-level type in JSON write

查看:190
本文介绍了JSON写入中的无效顶级类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to create a simple JSON object but I still get error and I know what's wrong in my code:

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];

例外是

JSON写入中的无效顶级类型

Invalid top-level type in JSON write

我也检查了JSONdic,在每种情况下它都不为零. 有什么建议吗?

I checked also JSONdic and it's not nil in every case. Any suggestions?

推荐答案

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

Ok I solved. It was a problem related to this line:

return [GCDWebServerDataResponse responseWithJSONObject:JSONdata];

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

this response of GCDWebServer doesn't want a JSON NSData but a NSDictionary: the error is just because responseWithJSONObject process the input for create a JSON object (and I passed a JSON "pre-processed" object). So my error is not related to my initial code so I updated it just now for future reference, I solved using:

return [GCDWebServerDataResponse responseWithJSONObject:JSONdic]; 

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

According to the documentation for similar problem be sure to follow this rules:

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

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

  • 顶级对象是NSArray或NSDictionary.
  • 所有对象都是 NSString,NSNumber,NSArray,NSDictionary或NSNull的实例.
  • 所有字典键都是NSString的实例.
  • 数字不是NaN或无穷大.
  • 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.

这篇关于JSON写入中的无效顶级类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆