[英]Unicode data from NSData to NSString
So if I have NSData from an HTTP request, then I do something like this: 因此,如果我有来自HTTP请求的NSData,则可以执行以下操作:
NSString *test = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
This will result in null if the data contains weird unicode data ( title is from reddit ): 如果数据包含奇怪的unicode数据( 标题来自reddit ),则将导致null:
{"title":"click..██me..and..then██________ ██check██_.your...██.__...██____ ██....██████████████....██____ ██████....██████....██████____ ██████████████████████____ ....██████████████████______ ........██..._recently....██________ ....██....viewed....links....██_____"},
How would I convert the data to a string? 我如何将数据转换为字符串? Ideally, it would best if the string wasn't null so I could parse it as JSON, but even a lossy conversion is fine with me in these cases.
理想情况下,最好是字符串不为null,这样我就可以将其解析为JSON,但在这种情况下,即使是有损转换也可以。
I'm not familiar with unicode (naive American I am), so any enlightenment about that would be a nice bonus :) 我不熟悉unicode(我是天真的美国人),所以对此的任何启发都会是一个不错的收获:)
If I copy and paste that text into a UTF-8 text file, read it with dataWithContentsOfURL:
and convert it to a string with initWithData:encoding:
, it works fine. 如果我将文本复制并粘贴到UTF-8文本文件中,请使用
dataWithContentsOfURL:
读取,然后使用initWithData:encoding:
将其转换为字符串,即可正常工作。 The most likely explanation is that you are not getting valid UTF-8 data. 最可能的解释是您没有获得有效的UTF-8数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.