我有以下 JSON 数组:
[u'steve@gmail.com']
“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 错误 3840。)“(字符 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' 字符。
最佳答案
[u'steve@gmail.com'] 是数组的解码 python 值,它不是有效的 JSON。
有效的 JSON 字符串数据将只是 ["steve@gmail.com"]
。
通过执行以下操作将数据从 python 转储回 JSON 字符串:
import json
python_data = [u'steve@gmail.com']
json_string = json.dumps(data)
python 字符串文字上的 u
前缀表示这些字符串是 unicode 而不是 python2.X (ASCII) 中的默认编码。
关于python - 使用 unicode 字符解码 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10936116/