NSData to NSString with JSON response

爷,独闯天下 提交于 2019-12-17 16:22:17

问题


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"?


回答1:


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




回答2:


I don't quite understand what the problem is. AFNetworking has given you a valid JSON packet. If you want the above code to output the character instead of the \u… escape sequence, you should coax the server feeding you the result to change its output. But this shouldn't be necessary. What you most likely want to do next is run it through a JSON deserializer…

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

…and you should get the following dictionary back: @{@"result":@"說"}. Note that the result key holds a string with a single character, which I'm guessing is what you want.

BTW: In future, I suggest you copy-paste output into your question rather than transcribing it by hand. It'll avoid several needless rounds of corrections and confusion.



来源:https://stackoverflow.com/questions/17337782/nsdata-to-nsstring-with-json-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!