Volley中的UTF-8 JsonObjectRequest支持

时间:2016-01-24 21:57:38

标签: android json android-volley

我有一个utf-8 json文件。

如何使用utf-8支持打印?

{
    "found": 2,
    "posts": [{
        "title": "title",
        "text": "text"
    },  {
        "title": "title",
        "text": "text"
    }]
}

数据(json文件)由我自己创建,我用UTF-8编码保存它们:

CGSize(width: 360, height: 480)

我在UTF-8上更改了Android文件编码设置,但没有任何改变。如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

您可以通过覆盖JsonObjectRequest类的parseNetworkResponse方法来完成此操作。首先创建一个扩展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));
        }
    }
}

然后使用您的新类代替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");

        }
    }     
);