NSUTF8StringEncoding返回nil NSString

时间:2012-03-14 12:15:32

标签: objective-c ios cocoa-touch utf-8

我正在使用最新的SDK和XCode 4.2开发iOs 4应用程序。

我使用网络服务检索一些数据,然后我收到了这些数据。但是,当我这样做时

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

receivedData有944字节,但json_string为零。

从网络服务我获取此字符串(从浏览器窗口复制和粘贴):

{"posts": [ { "ID": "324","fecha": "10/02/2012","titulo": "Preparada para la lluvia","texto": "¡Al mal tiempo buena cara! Eso pensé al vestirme el otro día que hiz...","foto": "2012/02/image20.jpg" } ] }

我试图在这里验证JSON http://jsonformatter.curiousconcept.com/,但我觉得它无效。告诉我这个格式化的输出:

{
   "posts":[
      {
         "ID":"324",
         "fecha":"10/02/2012",
         "titulo":"Preparada para la lluvia",
         "texto":,
         "foto":"2012/02/image20.jpg"
      }
   ]
}

这个错误:

Error:Strings should be wrapped in double quotes.[Code 17, Structure 20]
Error:Invalid characters found.[Code 18, Structure 20]

有关正在发生的事情的任何线索?

2 个答案:

答案 0 :(得分:9)

确保您拥有有效的UTF8数据,并使用

等功能检查
    NSStringEncoding encoding;
    NSString *pageData = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:NULL];
    NSLog(@"Encoding %d",encoding);(Note: NSUTF8StringEncoding = 4)

可用编码,

*/
enum {
    NSASCIIStringEncoding = 1,      /* 0..127 only */
    NSNEXTSTEPStringEncoding = 2,
    NSJapaneseEUCStringEncoding = 3,
    NSUTF8StringEncoding = 4,
    NSISOLatin1StringEncoding = 5,
    NSSymbolStringEncoding = 6,
    NSNonLossyASCIIStringEncoding = 7,
    NSShiftJISStringEncoding = 8,          /* kCFStringEncodingDOSJapanese */
    NSISOLatin2StringEncoding = 9,
    NSUnicodeStringEncoding = 10,
    NSWindowsCP1251StringEncoding = 11,    /* Cyrillic; same as AdobeStandardCyrillic */
    NSWindowsCP1252StringEncoding = 12,    /* WinLatin1 */
    NSWindowsCP1253StringEncoding = 13,    /* Greek */
    NSWindowsCP1254StringEncoding = 14,    /* Turkish */
    NSWindowsCP1250StringEncoding = 15,    /* WinLatin2 */
    NSISO2022JPStringEncoding = 21,        /* ISO 2022 Japanese encoding for e-mail */
    NSMacOSRomanStringEncoding = 30,

    NSUTF16StringEncoding = NSUnicodeStringEncoding,      /* An alias for NSUnicodeStringEncoding */

    NSUTF16BigEndianStringEncoding = 0x90000100,          /* NSUTF16StringEncoding encoding with explicit endianness specified */
    NSUTF16LittleEndianStringEncoding = 0x94000100,       /* NSUTF16StringEncoding encoding with explicit endianness specified */

    NSUTF32StringEncoding = 0x8c000100,                   
    NSUTF32BigEndianStringEncoding = 0x98000100,          /* NSUTF32StringEncoding encoding with explicit endianness specified */
    NSUTF32LittleEndianStringEncoding = 0x9c000100        /* NSUTF32StringEncoding encoding with explicit endianness specified */
};
typedef NSUInteger NSStringEncoding;

答案 1 :(得分:1)

我认为您的问题是Web服务无法返回有效的UTF-8文本。您应该检查服务器端的编码。