2017-12-17 4 views
0

サーバーからJSONを解析する代わりに、このクラスでローカル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); 
    } 
+1

あなたはgsonライブラリを試しましたか? –

+1

Gsonを試す - https://github.com/google/gson –

答えて

0

あなたの代わりに、サーバからJSONをパースのローカルJSONをしたい場合は、後で、Gsonを使用してJSONを解析することができます2 ways-

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でやったように。