java - Python 编码的 utf-8 string\xc4\x91 在 Java 中

标签 java python string utf-8 utf8-decode

如何从 Python 创建的字符串 'Oslobo\xc4\x91enja' 中获取正确的 Java 字符串? 如何解码?我已经尝试过我认为的一切,到处寻找,我已经被这个问题困住了 2 天。请帮忙!

这是返回 JSON 的 Python 网络服务方法,使用 Google Gson 的 Java 客户端从中解析它。

def list_of_suggestions(entry):
   input = entry.encode('utf-8')
   """Returns list of suggestions from auto-complete search"""
   json_result = { 'suggestions': [] }
   resp = urllib2.urlopen('https://maps.googleapis.com/maps/api/place/autocomplete/json?input=' + urllib2.quote(input) + '&location=45.268605,19.852924&radius=3000&components=country:rs&sensor=false&key=blahblahblahblah')
   # make json object from response
   json_resp = json.loads(resp.read())

   if json_resp['status'] == u'OK':
     for pred in json_resp['predictions']:
        if pred['description'].find('Novi Sad') != -1 or pred['description'].find(u'Нови Сад') != -1:
           obj = {}
           obj['name'] = pred['description'].encode('utf-8').encode('string-escape')
           obj['reference'] = pred['reference'].encode('utf-8').encode('string-escape')
           json_result['suggestions'].append(obj)

   return str(json_result)

Java客户端解决方案

private String python2JavaStr(String pythonStr) throws UnsupportedEncodingException {
    int charValue;
    byte[] bytes = pythonStr.getBytes();
    ByteBuffer decodedBytes = ByteBuffer.allocate(pythonStr.length());
    for (int i = 0; i < bytes.length; i++) {
        if (bytes[i] == '\\' && bytes[i + 1] == 'x') {
            // \xc4 => c4 => 196
            charValue = Integer.parseInt(pythonStr.substring(i + 2, i + 4), 16);
            decodedBytes.put((byte) charValue);
            i += 3;
        } else
            decodedBytes.put(bytes[i]);
    }
    return new String(decodedBytes.array(), "UTF-8");
}

最佳答案

您正在返回 python 数据结构的字符串版本。

返回一个实际的 JSON 响应; 保留 Unicode 值:

if json_resp['status'] == u'OK':
    for pred in json_resp['predictions']:
        desc = pred['description'] 
        if u'Novi Sad' in desc or u'Нови Сад' in desc:
            obj = {
                'name': pred['description'],
                'reference': pred['reference']
            }
            json_result['suggestions'].append(obj)

return json.dumps(json_result)

现在 Java 不必解释 Python 转义码,而是可以解析有效的 JSON。

关于java - Python 编码的 utf-8 string\xc4\x91 在 Java 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18594177/

相关文章:

java - 将大型文档库从一个 Liferay 6.1 实例导出到另一个实例

java - 访问在 Guice 的根对象图中不可配置的 Map<String, Interface-Impl>

java - 在运行时配置生存时间属性

python - 是否可以将参数解包运算符(又名飞溅运算符)实现为函数?

php - 从 Python/AppEngine 迁移到 PHP 的最佳框架

c# - ASP.NET Unicode 字符串显示不正确

java - 如何通过Java或SQL获取数据库表中定义的Json顺序?

Python:从有序列表中删除不在无序列表中的条目

java - 我怎样才能摆脱 "white spaces"

javascript - 从 jquery html() 设置/获取值的字符串比较失败?