簡體   English   中英

Objective-C:NSString不能完全從UTF-8解碼

[英]Objective-C: NSString not being entirely decoded from UTF-8

我正在查詢Web服務器,該服務器返回JSON字符串作為NSData 該字符串采用UTF-8格式,因此將其轉換為NSString如下所示。

NSString *receivedString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]; 

但是,某些utf-8轉義符仍保留在輸出的JSON字符串中,這導致我的應用程序行為異常。 \’之類的\’仍保留在字符串中。 我已經嘗試了所有方法來刪除它們,並用它們的實際字符替換它們。

我唯一能想到的就是用他們的角色手動替換UTF-8轉義符的出現,但是如果有一種更快的方法,這將是很多工作!

這是一個錯誤解析的字符串的示例:

{"title":"The Concept, Framed, The Enquiry, Delilah\u2019s Number 10  ","url":"http://livebrum.co.uk/2012/05/31/the-concept-framed-the-enquiry-delilah\u2019s-number-10","date_range":"31 May 2012","description":"","venue":{"title":"O2 Academy 3 ","url":"http://livebrum.co.uk/venues/o2-academy-3"}

如您所見,URL尚未完全轉換。

謝謝,

\’語法不是UTF-8編碼的一部分,它是JSON特定語法的一部分。 NSString解析UTF-8,而不是JSON,因此無法理解。

您應該使用NSJSONSerialization解析JSON,然后從輸出中提取所需的字符串。

所以,例如:

NSError *error = nil;
id rootObject = [NSJSONSerialization
                      JSONObjectWithData:receivedData
                      options:0
                      error:&error];

if(error)
{
    // error path here
}

// really you'd validate this properly, but this is just
// an example so I'm going to assume:
//
//    (1) the root object is a dictionary;
//    (2) it has a string in it named 'url'
//
// (technically this code will work not matter what the type
// of the url object as written, but if you carry forward assuming
// a string then you could be in trouble)

NSDictionary *rootDictionary = rootObject;
NSString *url = [rootDictionary objectForKey:@"url"];

NSLog(@"URL was: %@", url);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM