Sviatoslav
Sviatoslav

Reputation: 1312

How to read \uxxxx from json

I have json in format like this: {"0":{"title":"\u0417\u041d: \u0415\u0432\u0440\u043e\ ...

How to encode \uxxxx to the readable view?

json I am taking in the next way:

HttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet("http://android.forum-example.org/?a=1&b=2&c=3");
HttpResponse response = httpClient.execute(request);
resJson = HttpHelper.requestStr(response);
Log.v("JSON:", resJson);

requestStr(response):

public static String requestStr(HttpResponse response){
        String result = "";
        try{
            InputStream in = response.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            StringBuilder str = new StringBuilder();
            String line = null;
            while((line = reader.readLine()) != null){
                str.append(line + "\n");
            }
            in.close();
            result = str.toString();
        }catch(Exception ex){
            result = "Error";
        }
        return result;
}

Even result = new String(resJson.getBytes("UTF-8"), "UTF-8"); doesn't help. But when I use it with handmade string (example String str="\u0435\u043b\u0438 \u0415\u0432\"), then it works.

Upvotes: 1

Views: 722

Answers (1)

user370305
user370305

Reputation: 109247

Try this, and let me know what happen,

HttpResponse response = httpClient.execute(request);

HttpEntity entity = response.getEntity();
// convert entity response to string
  if (entity != null) {
    InputStream is = entity.getContent();
    // convert stream to string
    result = convertStreamToString(is); 
    result = result.replace("\n", "");
    }

and this is, convertStreamToString(is);

public static String convertStreamToString(InputStream is) throws Exception {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        StringBuilder sb = new StringBuilder();
        String line = null;

        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }

        is.close();
        return sb.toString();
    }

Upvotes: 1

Related Questions