2017-09-05 65 views
-1

今天,我知道,改造使用GSON(或任何其它轉換器),序列化或反序列化JSON響應(應答用okhttp或任何相關的庫了)。 現在,當我天真的時候(從某種意義上說還是我),我曾經使用過Volley,當時我從來沒有使用過Gson或任何相關的庫和okhttp.但是我曾經得到我的迴應,併成功地將它充氣到我的身上觀點。使用凌空沒有GSON

1.現在不排球內部做什麼改造並使用GSON和Okhttp? 如果不是? 2.那我怎麼能得到值解析而不使用任何東西?

下面是我以前寫的樣本代碼: -

JsonObjectRequest jsonObjectRequest=new JsonObjectRequest(
      Request.Method.POST, URL_THUMB, null, new Response.Listener<JSONObject>() { 

     @Override 
     public void onResponse(JSONObject response) { 
      try { 
       JSONArray jsonArray=response.getJSONArray("server_response"); 
       for(int i=0;i<jsonArray.length();i++) 
       { 
        JSONObject jsonObject=(JSONObject)jsonArray.get(i); 
        String id=jsonObject.getString("id"); 
        String artist_name=jsonObject.getString("artist_name"); 
        String img_id=jsonObject.getString("img_id"); 

        listId.add(id); 
        listArtistName.add(artist_name); 
        listImgID.add(img_id); 

       } 

       recyclerView.setAdapter(comedy_adapter); 

      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 
     } 
    }, new Response.ErrorListener() { 
     @Override 
     public void onErrorResponse(VolleyError error) { 

     } 
    } 
    ); 

,現在只是誇大這些列表值我的意見。

我哪裏錯了? (我不認爲我是錯了,因爲一切都很順利和代碼始終運行良好)

回答

1

在您的例子您解析響應爲JSON數組和對象手動。像Gson這樣的轉換器可以讓您將響應解析爲一行中自定義對象的變量。

舉例來說,如果我有以下型號:

public class Model { 
    private int id; 
    private String name; 
} 

我可以使用下面的代碼解析字符串響應:

Model model = gson.fromJson(str, Model.class); 

否則,您必須做手工,喜歡什麼你此刻在做:

JSONObject jsonObject = response.getJSONObject("str"); 
int id = jsonObject.getInt("id"); 
String name = jsonObject.getString("name"); 
Model model = new Model(id, name); 

在改造2,你甚至不必調用fromJson - 您可以在onResponse中接收您期望的對象作爲輸入參數。處理更復雜的模型時非常有用。