NSData到NSString与JSON响应 [英] NSData to NSString with JSON response

查看:157
本文介绍了NSData到NSString与JSON响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我得到结果:

  {result:\\\說} 

将数据编码到正确的字符串的正确方法,而不是像\uxxxx这样的unicode字符串?

解决方案

如果你转换JSON数据

  {result:\\\說} 
/ pre>

NSDictionary (例如使用 NSJSONSerialization )并打印字典

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

那么你会得到输出

  {
result =\U8aaa;
}

原因是描述 NSDictionary 的方法对所有非A​​SCII字符使用\Unnnn转义序列
。但是这只是在控制台中的显示,字典是正确



如果您打印关键

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

然后你会得到预期的输出

 


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

解决方案

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

这篇关于NSData到NSString与JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆