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

时间:2013-08-01 20:06:50

标签: iphone ios json nsmutabledictionary nsjsonserialization

当我尝试使用NSMutableDictionaryNSJSONSerialization转换为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))

1 个答案:

答案 0 :(得分:1)

dataWithJSONObject方法返回NSData,因此我建议:

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

    return [NSString stringWithUTF8String:[result bytes]];
    

    你应该这样做:

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