iphone - 使用 NSJSONSerialization 将 NSMutableDictionary 转换为 JSON 返回不同的结果

标签 iphone ios json nsmutabledictionary nsjsonserialization

当我尝试使用 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))

最佳答案

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

  1. 转换 NSData进入NSString ,你应该使用initWithData而不是stringWithUTF8String 。所以,而不是:

    return [NSString stringWithUTF8String:[result bytes]];
    

    你应该这样做:

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

关于iphone - 使用 NSJSONSerialization 将 NSMutableDictionary 转换为 JSON 返回不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18003540/

相关文章:

iphone - 如何将图像放入此 UIPickerView 中?

ios - 使用 UIBezierPath 在 Swift 中制作旭日形

html - iOS 6.1.3 中 HTML 中的 WebApp 上传错误的假路径

android - 如何将来自数据库的日期格式更改为android

iphone - 如何使 UIImageView 变暗

iphone - UIPickerview自定义

ios - Cocoapods - 如何让它向项目添加 iOS 框架?

ios - 没有更多上下文的动画选项不明确

json - package.json 版本和 teamcity

java - Jackson 反序列化器 - 将空集合更改为空集合