android - How to create unicode characters from JsonObject for address info? -
i'm using this code address info , working fine, casting non english characters not correct.
how fix unicode problem??
public jsonobject getlocationinfo() { //http request httpget httpget = new httpget("http://maps.google.com/maps/api/geocode/json?latlng="+lat+","+lng+"&sensor=true"); httpclient client = new defaulthttpclient(); httpresponse response; stringbuilder stringbuilder = new stringbuilder(); try { response = client.execute(httpget); httpentity entity = response.getentity(); inputstream stream = entity.getcontent(); int b; while ((b = stream.read()) != -1) {//even character.tochars(b) not working stringbuilder.append((char) b); } } catch (clientprotocolexception e) { } catch (ioexception e) { } //create json string return. jsonobject jsonobject = new jsonobject(); try { jsonobject = new jsonobject(stringbuilder.tostring()); } catch (jsonexception e) { e.printstacktrace(); } return jsonobject; }
call function follows complete address:
jsonobject ret = getlocationinfo(); //get json returned api call jsonobject location; string location_string; //parse value corresponding `formatted_address` key. try { location = ret.getjsonarray("results").getjsonobject(0); location_string = location.getstring("formatted_address"); log.d("test", "formattted address:" + location_string); } catch (jsonexception e1) { e1.printstacktrace(); }
instead of reading byte wise stringbuilder, use
bytearrayoutputstream baos; ... string jsontext = new string(baos.tobytearray(), standardcharsets.utf_8);
in concreto:
bytearrayoutputstream baos = new bytearrayoutputstream(); try { response = client.execute(httpget); httpentity entity = response.getentity(); inputstream stream = entity.getcontent(); byte[] buffer = new byte[1024]; int nread; while ((nread = stream.read(buffer)) > 0) { baos.write(buffer, 0, nread); } } catch (clientprotocolexception | ioexception e) { } //create json string return. jsonobject jsonobject = new jsonobject(); try { string jsontext = new string(baos.tobytearray(), standardcharsets.utf_8); jsonobject = new jsonobject(jsontext);
the above uses buffer too; there exists bufferedinputstream too.
Comments
Post a Comment