【问题标题】:Python encoded utf-8 string \xc4\x91 in Java在 Java 中 Python 编码的 utf-8 字符串 \xc4\x91
【发布时间】:2013-09-06 19:11:51
【问题描述】:

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

这是 Python 的 Web 服务方法,它返回 JSON,带有 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");
}

【问题讨论】:

  • 您将 UTF-8 数据显示为 Python 字符串文字,将其解码为 Unicode 会得到 Oslobođenja。大概 Java 可以处理 UTF-8 数据?
  • @Ognjen:坚持使用json 模块以生成有效的 JSON。 u'Oslobo\u0111enja'not JSON,这是一个 Python 字符串文字。 "Oslobo\u0111enja".
  • @Ognjen:你想做什么?如果您在 python 中加载 JSON,那么u'Oslobo\u0111enja' 正是您想要的。那是一个有效的 Unicode 值。我假设您正在生成 JSON 以便读取一些Java 代码,并且在Java 方面遇到了困难。
  • @Ognjen:你能更新你的问题以显示代码吗?将 Unicode 值传递给 json.dumps() 以生成有效的 JSON 供 Java 处理,或者使用 encoding 参数告诉 json.dumps() 如何解码字节字符串。

标签: java python string utf-8 utf8-decode


【解决方案1】:

您正在返回 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。

【讨论】:

  • 正如你会说英语的人所说的那样:工作就像一个魅力! :) 谢谢,这是更优雅的解决方案。我还在学习 Python。
【解决方案2】:

Python 通过将其 UTF-8 字节 转换为一系列 \xVV 值来转义 unicode 字符,其中 VV 是字节的十六进制值。这非常与 java unicode 转义不同,后者只是每个字符一个 \uVVVV,其中 VVVV 是十六进制 UTF-16 编码。

考虑:

\xc4\x91

在十进制中,这些十六进制值是:

196 145

然后(在 Java 中):

byte[] bytes = { (byte) 196, (byte) 145 };
System.out.println("result: " + new String(bytes, "UTF-8"));

打印:

result: đ

【讨论】:

  • 谢谢你10000次!给我买啤酒,给我寄账单:) 再次感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-18
  • 2014-06-09
  • 2013-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多