【问题标题】:Converting NSMutableDictionary to JSON with NSJSONSerialization returns different results使用 NSJSONSerialization 将 NSMutableDictionary 转换为 JSON 会返回不同的结果
【发布时间】:2013-08-01 20:06:49
【问题描述】:

当我尝试使用 NSJSONSerializationNSMutableDictionary 转换为 JSON 时,它会返回不同的结果:

代码:

-(NSString*)JSONRepresentation{

    return [self JSONRepresentation:NO];
}

-(NSString*)JSONRepresentation:(BOOL)whiteSpaces{

    NSError* error = nil;
    NSData * result = nil;

    if(whiteSpaces)
        result = [NSJSONSerialization dataWithJSONObject:self options:NSJSONWritingPrettyPrinted error:&error];
    else
        result = [NSJSONSerialization dataWithJSONObject:self options:kNilOptions error:&error];

    if (error != nil){
        NSLog(@"Error:%@",error);
        return nil;
    }

    return [NSString stringWithUTF8String:[result bytes]];
}

我就是这样使用它的:

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setObject:@"xxx" forKey:@"experiment"];

NSLog(@"(%@)", [dict JSONRepresentation]);

连续尝试的结果:

2013-08-01 12:31:45.066 Hercules Demo[8763:c07] ((null))
2013-08-01 12:31:49.988 Hercules Demo[8763:c07] ((null))
2013-08-01 12:31:52.838 Hercules Demo[8763:c07] ({"experiment":"xxx"})
2013-08-01 12:31:59.432 Hercules Demo[8763:c07] ({"experiment":"xxx"})
2013-08-01 12:32:03.160 Hercules Demo[8763:c07] ((null))
2013-08-01 12:32:06.232 Hercules Demo[8763:c07] ({"experiment":"xxx"})
2013-08-01 12:32:08.395 Hercules Demo[8763:c07] ((null))

【问题讨论】:

  • 您是否还记录了要转换为 JSON 的对象?
  • 另外,验证失败后,您将继续序列化。
  • 另外,请向我们展示JSONRepresentation 的代码。上面显示了JSONRepresentation: 的代码,这是完全不同的。
  • 是的,如果您改为拨打JSONRepresentation:NO 会怎样?
  • 虽然 Hot Licks 无疑是正确的,但顺便说一句,我也倾向于 (a) 将 result 定义为 NSData(因为这是 dataWithJSONObject 返回的内容); (b) 使用[[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding] 而不是[NSString stringWithUTF8String:[result bytes]]

标签: iphone ios json nsmutabledictionary nsjsonserialization


【解决方案1】:

dataWithJSONObject 方法返回一个NSData,所以我建议:

  1. 要将NSData 转换为NSString,您应该使用initWithData 而不是stringWithUTF8String。所以,而不是:

    return [NSString stringWithUTF8String:[result bytes]];
    

    你应该这样做:

    return [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
    
  2. 为了清楚起见,您可能应该将result 定义为NSData * 而不是id

【讨论】:

    猜你喜欢
    • 2016-04-26
    • 2018-10-16
    • 1970-01-01
    • 2017-07-07
    • 2019-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-24
    相关资源
    最近更新 更多