Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/391.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java中Python编码的utf-8字符串\xc4\x91_Java_Python_String_Utf 8_Utf8 Decode - Fatal编程技术网

Java中Python编码的utf-8字符串\xc4\x91

Java中Python编码的utf-8字符串\xc4\x91,java,python,string,utf-8,utf8-decode,Java,Python,String,Utf 8,Utf8 Decode,如何从Python创建的字符串“Oslobo\xc4\x91enja”中获取正确的Java字符串? 如何解码?我试过了,我想一切,到处都找过了,我被这个问题困扰了两天。请帮忙 下面是Python的web服务方法,该方法返回JSON,带有Google Gson的Java客户机从中解析JSON def list_of_suggestions(entry): input = entry.encode('utf-8') """Returns list of suggestions from

如何从Python创建的字符串“Oslobo\xc4\x91enja”中获取正确的Java字符串? 如何解码?我试过了,我想一切,到处都找过了,我被这个问题困扰了两天。请帮忙

下面是Python的web服务方法,该方法返回JSON,带有Google Gson的Java客户机从中解析JSON

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");
}
私有字符串python2JavaStr(字符串pythonStr)引发不受支持的codingexception{
int值;
byte[]bytes=pythonStr.getBytes();
ByteBuffer decodedBytes=ByteBuffer.allocate(pythonStr.length());
for(int i=0;ic4=>196
charValue=Integer.parseInt(pythonStr.substring(i+2,i+4),16);
decodedBytes.put((字节)charValue);
i+=3;
}否则
decodedBytes.put(字节[i]);
}
返回新字符串(decodedBytes.array(),“UTF-8”);
}

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

考虑:

\xc4\x91
在十进制中,这些十六进制值为:

196 145
然后(在Java中):

印刷品:

result: đ

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

您将UTF-8数据显示为Python字符串文本,将其解码为Unicode将提供
Oslobođenja
。假设Java可以处理UTF-8数据?也许可以看看这个问题:@Ognjen:坚持使用
json
模块来生成有效的json
u'Oslobo\u011enja'
不是JSON,而是Python字符串文本<代码>“Oslobo\u011enja”是。@Ognjen:你想做什么?如果您正在用python加载JSON,那么
u'Oslobo\u011enja'
正是您想要的。这是一个有效的Unicode值。我假设您正在生成JSON以供某些Java代码阅读,并且正在与Java方面进行斗争。@Ognjen:您可以更新您的问题以显示用于此目的的代码吗?要么将Unicode值传递给
json.dumps()
以生成有效的json供Java处理,要么使用
encoding
参数告诉
json.dumps()
如何解码字节字符串。正如你们说英语的人所说:工作很有魅力!)谢谢,这是更优雅的解决方案。我还在学Python。谢谢你10000次!请帮我买啤酒,给我寄账单:)再次谢谢!
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)