2012-06-07 76 views
2

我有以下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'字符。

+0

我認爲你應該修復你的Python代碼來打印出Unicode,因爲那個JSON是無效的。 – nhahtdh

+0

你用python的'json'庫將內容序列化爲json嗎? – jhonkola

+0

嘗試在上面使用'str()'代替'unicode()'。 'getattr(self,p)'返回什麼類型的對象?該對象是否覆蓋__str__或__repr__? – stderr

回答

6

[u'[email protected]']是數組的解碼python值,它不是有效的JSON。

有效的JSON字符串數據只是["[email protected]"]

做轉儲從蟒蛇放回JSON字符串的數據:

import json 
python_data = [u'[email protected]'] 
json_string = json.dumps(data) 

Python的字符串文字的u前綴表示,這些字符串是unicode的,而不是在python2.X(ASCII)的默認編碼。

+0

那麼我正在使用Google App Engine,並將值存儲到StringListProperty中。我將每個字符串逐一存儲起來,並且由於某種原因,在開始時以「u」存儲它們。我怎樣才能阻止它存儲'你'在第一個地方? – Snowman

+0

它不存儲u字符,這是一個表示字符串是unicode編碼的整形前綴。請將您的問題更新爲您將Python中的數據返回到Objective-C代碼的方式。您需要使用'json.dumps/json.dump'將StringListProperty值編碼爲JSON。 – stderr

+0

好的,我編輯了我的問題 – Snowman