我有以下JSON數組:解碼JSON陣列與Unicode字符
[u'[email protected]']
「U」是顯然的Unicode字符,它被自動被Python創建。現在,我希望把這種回Objective-C和利用這一點,解碼成一個數組:
+(NSMutableArray*)arrayFromJSON:(NSString*)json
{
if(!json) return nil;
NSData *jsonData = [json dataUsingEncoding:NSUTF8StringEncoding];
//I've also tried NSUnicodeStringEncoding here, same thing
NSError *e;
NSMutableArray *result= [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&e];
if (e != nil) {
NSLog(@"Error:%@", e.description);
return nil;
}
return result;
}
但是,我得到一個錯誤:(Cocoa error 3840.)" (Invalid value around character 1.)
如何解決這個問題?
編輯:這是我帶來怎樣從Python的實體回的Objective-C:
首先,我將實體轉換成詞典:
def to_dict(self):
return dict((p, unicode(getattr(self, p))) for p in self.properties()
if getattr(self, p) is not None)
我這本詞典添加到列表中,設置我的responseDict ['entityList']的值到這個列表中,然後self.response.out.write(json.dumps(responseDict))
然而我得到的結果仍然有'u'字符。
我認爲你應該修復你的Python代碼來打印出Unicode,因爲那個JSON是無效的。 – nhahtdh
你用python的'json'庫將內容序列化爲json嗎? – jhonkola
嘗試在上面使用'str()'代替'unicode()'。 'getattr(self,p)'返回什麼類型的對象?該對象是否覆蓋__str__或__repr__? – stderr