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

Ogn*_*nić 6 python java string utf-8 utf8-decode

如何从Python创建正确的Java字符串创建字符串'Oslobo\xc4\x91enja'?怎么解码呢?我已经尝试过,我认为一切,到处都是,我已经被这个问题困住了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)
Run Code Online (Sandbox Code Playgroud)

这是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");
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 2

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

\n\n

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

\n\n
if json_resp['status'] == u'OK':\n    for pred in json_resp['predictions']:\n        desc = pred['description'] \n        if u'Novi Sad' in desc or u'\xd0\x9d\xd0\xbe\xd0\xb2\xd0\xb8 \xd0\xa1\xd0\xb0\xd0\xb4' in desc:\n            obj = {\n                'name': pred['description'],\n                'reference': pred['reference']\n            }\n            json_result['suggestions'].append(obj)\n\nreturn json.dumps(json_result)\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n