0

NSMutableDictionaryJSONに変換しようとすると、NSJSONSerialization異なる結果が返されます。

コード:

-(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))
4

1 に答える 1

1

dataWithJSONObjectメソッドは を返すので、次のことをおNSData勧めします。

  1. を に変換するNSDataには、ではなくNSStringを使用する必要があります。したがって、ではなく:initWithDatastringWithUTF8String

    return [NSString stringWithUTF8String:[result bytes]];
    

    やったほうがいい:

    return [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
    
  2. わかりやすくするために、おそらくresultaNSData *ではなくと定義する必要がありますid

于 2013-08-01T23:41:05.170 に答える