iOS2019. 5. 27. 20:20

1. NSDictionary -> NSString 

NSMutableDictionary *jsonDic = [[NSMutableDictionary alloc] init];
[jsonDic setValue:[NSNumber numberWithBool:TRUE] forKey:@"result"];
[jsonDic setValue:@"test message" forKey:@"message"];
NSString *jsonDicStr = [NSString stringWithFormat:@"%@", jsonDic];


NSLog(@"jsonDicStr: %@", jsonDicStr);
jsonDicStr: {
message = "test message";
result = 1;
}


2. NSDictionary -> NSData -> NSString 

NSMutableDictionary *jsonDic = [[NSMutableDictionary alloc] init];
[jsonDic setValue:[NSNumber numberWithBool:TRUE] forKey:@"result"];
[jsonDic setValue:@"test message" forKey:@"message"];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:jsonDic options:NSJSONWritingPrettyPrinted error:nil];
NSString* jsonDataStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

NSLog(@"jsonDataStr: %@", jsonDataStr);
jsonDataStr: {
"result" : true,
"message" : "test message"
}

Json(NSDictionary) 데이터를 바로 NSString 변환하면 Json key에 double quote 제거 된다.
그러므로 Json data를 그대로 출력하려면 NSData로 NSJSONSerialization을 통해서 변환한 후에 다시 NSString으로 변환하여야 제대로된 json  string을 출력할 수 있다.
예) json string을 http통신을 통해 파라미터로 전달 하는 경우

Posted by 위푸