2015-10-17 72 views
1

很簡單的問題,我想?我如何創建JSON文件並插入(附加)我從Volley請求的新數據(GET)。因此,回顧一下,創建文件並將其附加到我的GET響應中。謝謝!如何創建JSON文件並用排除新數據填充

// Formulate the request and handle the response. 
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, (String)null, 
      new Response.Listener<JSONObject>() { 
       @Override 
       public void onResponse(JSONObject response) { 
        Toast.makeText(getActivity(), response.toString() , Toast.LENGTH_LONG).show(); 
       } 

      }, new Response.ErrorListener() { 
     @Override 
     public void onErrorResponse(VolleyError error) { 
      Toast.makeText(getActivity(), "Error Fetching Data", Toast.LENGTH_LONG).show(); 
     } 
    }); 

    mRequestQueue.add(jsonObjectRequest); 

我如何讀取文件時存在在用戶的手機上(漂亮不重要,但仍然給人上下文)

public String loadJSONFromAsset() { 

    String json = null; 
    try { 
     InputStream is = getActivity().getAssets().open("test12.json"); 
     int size = is.available(); 
     byte[] buffer = new byte[size]; 
     is.read(buffer); 
     is.close(); 
     json = new String(buffer, "UTF-8"); 
    } catch (IOException ex) { 
     Toast.makeText(getActivity(), "Error Fetching Data", Toast.LENGTH_LONG).show(); 
     return null; 
    } 

    return json; 

} 

謝謝!

回答

0

問題是因爲你的loadJSONFromAsset不能生成json。它只讀取文件並將數據放入字符串中。 YOu必須轉換成JSON與

final JsonObject savedJson = new JsonObject(json) 

然後在你的凌空onResponse你可以把它們放在一起。看到這個答案(由別人)如何做到這一點:https://stackoverflow.com/a/2403453/267540