NSData for NSString with JSON Response

NSData * jsonData strong> - This 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 correct way to encode data into the correct string, rather than a unicode string such as "\ uxxxx"?

+7
source share
2 answers

If you convert JSON data

 { "result" : "\u8aaa" } 

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

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

then you get a conclusion

 { result = "\U8aaa"; } 

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

If you print the key value

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

then you get the expected result

 čŖŖ 
+19
source

I do not quite understand what the problem is. AFNetworking has provided you with a valid JSON package. If you want the code above to output a character instead of the escape sequence \u… , you must persuade the server to provide the result to change its output. But this is optional. What you most likely want to do next, run it through the JSON deserializer ...

 NSDictionary * data = [NSJSONSerialization JSONObjectWithData:jsonData …]; 

... and you should get the following dictionary back: @{@"result":@"čŖŖ"} . Note that the result key contains a string with a single character, which I assume is what you want.

BTW: In the future, I suggest you copy-paste the output into your question, rather than decrypt it manually. This will avoid a few extra rounds of corrections and confusion.

0
source

All Articles