Reputation: 41
I have an utf-8 json file.
How can I print it with utf-8 support?
output = (TextView) view.findViewById(R.id.jData);
JsonObjectRequest jor = new JsonObjectRequest(Request.Method.GET, loginURL, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try{
JSONArray ja = response.getJSONArray("posts");
for(int i=0; i < ja.length(); i++){
JSONObject jsonObject = ja.getJSONObject(i);
String title = jsonObject.getString("title");
String text = jsonObject.getString("text");
data += "Blog Number "+(i+1)+" \n title= "+title +" \n text= "+ text +" \n\n\n\n ";
}
output.setText(data);
}catch(JSONException e){e.printStackTrace();}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley","Error");
}
}
);
requestQueue.add(jor);
The data (json file) were created by myself and I saved them with UTF-8 encoding:
{
"found": 2,
"posts": [{
"title": "title",
"text": "text"
}, {
"title": "title",
"text": "text"
}]
}
I changed Android File Encoding Settings on UTF-8, but nothing changed. How fix this problem?
Upvotes: 0
Views: 1658
Reputation: 7683
You can do this by overriding the parseNetworkResponse
method of the JsonObjectRequest class. First make a new class which extends JsonObjectRequest:
public class Utf8JsonObjectRequest extends JsonObjectRequest {
public Utf8JsonObjectRequest(int method,
String url,
Response.Listener<JSONObject> listener,
Response.ErrorListener errorListener) {
super(method, url, listener, errorListener);
}
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(
response.data,
"UTF-8"
);
return Response.success(
new JSONObject(json),
HttpHeaderParser.parseCacheHeaders(response)
);
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
}
Then use your new class in place of JsonObjectRequest:
Utf8JsonObjectRequest jor = new Utf8JsonObjectRequest(
Request.Method.GET,
loginURL,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
//...
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Volley","Error");
}
}
);
Upvotes: 2