【问题标题】:JSON Error in iOS: Invalid top-level type in JSON writeiOS 中的 JSON 错误:JSON 写入中的顶级类型无效
【发布时间】:2012-08-13 10:54:15
【问题描述】:

我无法找出这个错误:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization writeJSONObject:toStream:options:error:]: Invalid top-level type in JSON write'

这与这段代码有关(基本上我正在创建一些 JSON 并将其发送到服务器)。我已经和服务器检查过socket是否打开了,是的!

NSDictionary *blobData = [NSDictionary dictionaryWithObjectsAndKeys:
                          sendString,@"string",
                          nil];
NSString *blobString = [[NSString alloc]
                        initWithData:[NSJSONSerialization dataWithJSONObject:blobData options:kNilOptions error:&error]
                        encoding:NSUTF8StringEncoding];
NSLog(@"Blob Created: %@", blobString);
NSDictionary *requestData = [NSDictionary dictionaryWithObjectsAndKeys:
                             @"send_string",@"request_type",
                             [NSNumber numberWithInt:0],@"security_level",
                             @"ios",@"device_type",
                             //No Email Provided, This is just for testing
                             blobData,@"blob",
                             nil];

NSData *JSONRequestData = NULL;
if ([NSJSONSerialization isValidJSONObject:requestData]) {
    NSLog(@"Proper JSON Object");
    JSONRequestData = [NSJSONSerialization dataWithJSONObject:requestData options:kNilOptions error:&error];
}
else {
    NSLog(@"requestData was not a proper JSON object");
    return FALSE;
}
NSLog(@"Error:%@",[[error userInfo] objectForKey:@"NSDebugDescription"]);
NSLog(@"Contents of JSONRequestData: %@",[[NSString alloc] initWithData:JSONRequestData encoding:NSUTF8StringEncoding]);
[NSJSONSerialization writeJSONObject:JSONRequestData toStream:outputStream options:0 error:&error];

我创建的 JSON 对象错了吗?也许我处理“blob”的方式有问题

这是我创建 JSONRequestData 后 NSLogs 打印的内容

{"security_level":"0","request_type":"send_string","device_type":"ios","blob":{"string":"hello"}}

【问题讨论】:

    标签: ios json


    【解决方案1】:

    writeJSONObject 期望您要发送的实际未序列化对象,因此在这种情况下,您希望将 requestData 对象传递给它,而不是 JSONRequestData 之类的:

    NSJSONSerialization writeJSONObject:requestData toStream:outputStream options:0 error:&error];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-16
      • 2017-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多