JSON中关于GB2312的转化

JSON中的NSSTRING是默认格式是UNICODE,但是JSON给的是GB2312,因此在数据上会出现差异。

查了资料,都说可以用kCFStringEncodingGB_18030_2000可以转化,但是还是会有问题,最后在 对比内存发现,每个正确的数据前面多了00这个应该是JSON转给NSString出现的问题。

正确数据
C3 DC C2 EB B2 BB B6 D4 A3 AC C7 EB D6 D8 D0 C2 CA E4 C8 EB
错误数据
C3 00 DC 00 C2 00 EB 00 B2 00 BB 00 B6 00 D4 00 A3 00 AC 00 C7 00 EB 00 D6 00 D8 00 D0 00 C2 00 CA 00 E4 00 C8 00 EB 00




解决办法如下:


+ (NSString*)getFormJSONbyGB2312:(NSString*)string
{
    int nLen = [string length];
    if (nLen > 0)
    {
        char* pWChar = (char*)[string cStringUsingEncoding:NSUTF16StringEncoding];
        char* pChar = new char[nLen+1];
        memset(pChar, 0, nLen+1);
        for (int i=0; i<nLen; i++)
        {
            pChar[i] = pWChar[i*2];
        }
        
        NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
        
        NSString *textMsg  = [NSString stringWithCString:(char*)pChar encoding:enc]; 

        delete pChar;
        
        return textMsg;
    }
    
    return nil;
}



你可能感兴趣的:(JSON中关于GB2312的转化)