Using Volley without Gson

*爱你&永不变心* 提交于 2019-12-13 08:37:11

问题


Today I got to know that Retrofit uses gson(or any other convertor) to serialize or deserialize the json response (response that was got using okhttp or any related library). Now, when I was naive(in some sense still am) and I used to use Volley and at that time I never used Gson or any related library and same for okhttp.But i used to get my response and inflate it successfully on my views.

1. Now does Volley internally do what Retrofit does using Gson and Okhttp? If not? 2. Then how did i able to get values parsed without using anything?

Below is the sample Codes that i used to write:-

  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) {

        }
    }
    );

and now just inflate these list values to my views.

Where did I go wrong? (I don't think I was wrong as things went well and code always run fine)


回答1:


In your example you're parsing the response into JSON arrays and objects manually. Converters such as Gson let you parse the response into a variable of a custom object in a single line.

For example, if I have the following model:

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

I can parse a string response using the following code:

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

Otherwise, you have to do it manually, like what you're doing at the moment:

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

In Retrofit 2 you don't even have to call fromJson - you simple receive the object you expect as an input parameter in onResponse. It's very useful when dealing with more complex models.



来源:https://stackoverflow.com/questions/46053696/using-volley-without-gson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!