【问题标题】:Using Volley without Gson在没有 Gson 的情况下使用 Volley
【发布时间】:2018-02-13 16:10:57
【问题描述】:

今天我知道 Retrofit 使用 gson(或任何其他转换器)来序列化或反序列化 json 响应(使用 okhttp 或任何相关库获得的响应)。 现在,当我很天真(在某种意义上仍然是)并且我曾经使用 Volley 时,那时我从未使用过 Gson 或任何相关库,对于 okhttp 也是如此。但我曾经得到我的回应并成功地根据我的观点对其进行膨胀.

1.现在 Volley 在内部做 Retrofit 使用 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) {

        }
    }
    );

现在只需将这些列表值膨胀到我的视图中。

我哪里做错了? (我不认为我错了,因为事情进展顺利,代码总是运行良好)

【问题讨论】:

    标签: android android-volley retrofit


    【解决方案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);
    

    在 Retrofit 2 中,您甚至不必调用 fromJson - 您只需在 onResponse 中接收您期望的对象作为输入参数。在处理更复杂的模型时非常有用。

    【讨论】:

      猜你喜欢
      • 2016-11-29
      • 2021-04-12
      • 1970-01-01
      • 2015-11-12
      • 2021-12-27
      • 2016-06-12
      • 2021-10-30
      • 2010-12-09
      • 2018-03-02
      相关资源
      最近更新 更多