简体   繁体   中英

Unicode data from NSData to NSString

So if I have NSData from an HTTP request, then I do something like this:

NSString *test = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

This will result in null if the data contains weird unicode data ( title is from reddit ):

{"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.

I'm not familiar with unicode (naive American I am), so any enlightenment about that would be a nice bonus :)

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. The most likely explanation is that you are not getting valid UTF-8 data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM