本地json文件解析而不是远程服务器

问题描述 投票:0回答:1

如何使此类解析本地JSON文件而不是从服务器解析JSON?我尝试了很多方法,但它们都没有和我一起工作。

点击here

private void fetchContacts() {
        JsonArrayRequest request = new JsonArrayRequest(URL,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        if (response == null) {
                            Toast.makeText(getApplicationContext(), "Couldn't fetch the contacts! Pleas try again.", Toast.LENGTH_LONG).show();
                            return;
                        }

                        List<Contact> items = new Gson().fromJson(response.toString(), new TypeToken<List<Contact>>() {
                        }.getType());

                        // adding contacts to contacts list
                        contactList.clear();
                        contactList.addAll(items);

                        // refreshing recycler view
                        mAdapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                // error in getting json
                Log.e(TAG, "Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(), "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

        MyApplication.getInstance().addToRequestQueue(request);
    }
android json android-recyclerview
1个回答
0
投票

如果您想要一个本地JSON而不是从服务器解析JSON,您可以通过两种方式完成此操作 -

 1. **Create a String containing the JSON and then parse it**
String json = {"phonetype":"N95","cat":"WP"};

try {

    JSONObject obj = new JSONObject(json);

    Log.d("My App", obj.toString());

} catch (Throwable t) {
    Log.e("My App", "Could not parse malformed JSON: \"" + json + "\"");
}

 2. **Write your JSON in a local file and read it from it**
public String loadJSONFromAsset() {
    String json = null;
    try {
        InputStream is = getActivity().getAssets().open("yourfilename.json");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}

稍后您可以像使用onResonse一样使用Gson解析JSON。

© www.soinside.com 2019 - 2024. All rights reserved.