Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSData to NSString with JSON response

NSData* jsonData is the http response contains JSON data.

NSString* jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"jsonString: %@", jsonString);

I got the result:

{ "result": "\u8aaa" }

What is the proper way to encoding the data to the correct string, not unicode string like "\uxxxx"?

like image 842
shiami Avatar asked Jun 27 '13 08:06

shiami


1 Answers

If you convert the JSON data

{ "result" : "\u8aaa" }

to a NSDictionary (e.g. using NSJSONSerialization) and print the dictionary

NSError *error;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(@"%@", jsonDict);

then you will get the output

{
    result = "\U8aaa";
}

The reason is that the description method of NSDictionary uses "\Unnnn" escape sequences for all non-ASCII characters. But that is only for display in the console, the dictionary is correct!

If you print the value of the key

NSLog(@"%@", [jsonDict objectForKey:@"result"]);

then you will get the expected output

like image 158
Martin R Avatar answered Oct 19 '22 06:10

Martin R