How to get proper Java string from Python created string 'Oslobo\xc4\x91enja'? How to decode it? I've tryed I think everything, looked everywhere, I've been stuck for 2 days with this problem. Please help!
Here is the Python's web service method that returns JSON from which Java client with Google Gson parses it.
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)
Here is solution on Java client
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");
}
Oslobođenja
. Presumably Java can handle UTF-8 data? – Venosityjson
module to produce valid JSON.u'Oslobo\u0111enja'
is not JSON, that's a Python string literal."Oslobo\u0111enja"
is. – Venosityu'Oslobo\u0111enja'
is exactly what you want. That's a valid Unicode value right there. I assumed you were producing JSON for some Java code to read and were struggling with the Java side. – Venosityjson.dumps()
to produce valid JSON for Java to handle, or telljson.dumps()
with theencoding
parameter how to decode byte strings. – Venosity'Oslobo\xc4\x91enja'
is a Python literal string notation for UTF8 bytes. I had Python interpret that string back to a byte string value, then decoded from UTF8. – Venosity\u....
escape codes as well, and those any JSON parser can handle. It's theu'..'
oru"..."
strings that don't work for such parsers. – Venosity