【问题标题】:Android - GsonRequest returns nullAndroid - GsonRequest 返回 null
【发布时间】:2014-01-16 09:53:24
【问题描述】:

我在这里有一个 ListFragment,它需要一个 url 来使用 GSON 库解析 JSON。 Volley 用于后台任务:

public class LatestFragment extends ListFragment {

    public LatestFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_latest, container,
                false);

        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        arrItemList = new ArrayList<ItemListModel>();
        va = new LatestAdapter(getActivity(), arrItemList);

        loadItemList(1);
    }

    private void loadItemList(int page) {
        mRequestQueue = Volley.newRequestQueue(getActivity());
        pd = ProgressDialog.show(getActivity(), null, "Loading...");

        // TODO use Volley param
        currentPage = page;
        param = "?page=" + currentPage;

        String url = Constants.LATEST_ITEM_LIST + param;

        GsonRequest<ItemListModel> myReq = new GsonRequest<ItemListModel>(
                Method.GET, url, ItemListModel.class,
                createMyReqSuccessListener(), createMyReqErrorListener());

        mRequestQueue.add(myReq);

    }


    private Response.Listener<ItemListModel> createMyReqSuccessListener() {
        return new Response.Listener<ItemListModel>() {
            @Override
            public void onResponse(ItemListModel response) {
                try {
                    Log.d("response > ", response.toString());
                    pd.dismiss();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            };
        };
    }

    private Response.ErrorListener createMyReqErrorListener() {
        return new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {    
            }
        };
    }
}

当我运行应用程序时,它显示 responsenull

这里是ItemListModel

public class ItemListModel {

    private String user_id;
    private String item_id;
    private String name;
    private String price;
    private String category;
    private ThumbnailModel thumbnail; // not array list

    public ItemListModel(){}

    //getters

    @Override
    public String toString() { 
        return "ItemListModel [user_id=" + user_id + ", item_id=" + item_id
                + ", name=" + name + ", price=" + price + ", category="
                + category + ", thumbnail=" + thumbnail + "]";
    } // ALL NULL
}

反序列化这种 JSON 格式:

{
  "results": [
    {
      "user_id": "1",
      "item_id": "18630",
      "name": "Unnamed Item",
      "price": "0",
      "description": "",
      "created_at": "2014-01-16 15:31:36",
      "thumbnail": {
        "image50": "http://www.example.com/adsa.jpg",
        "image100": "hhttp://www.example.com/adsa.jpg"
      },...

这次我做错了什么?我应该坚持使用 Volley 的 JSONArrayRequest 吗?嗯。

【问题讨论】:

    标签: java android json gson android-volley


    【解决方案1】:

    您为 Json 响应创建的模型存在问题。

    {
      "results": [
        {
          "user_id": "1",
          "item_id": "18630",
          "name": "Unnamed Item",
          "price": "0",
          "description": "",
          "created_at": "2014-01-16 15:31:36",
          "thumbnail": {
            "image50": "http://www.example.com/adsa.jpg",
            "image100": "hhttp://www.example.com/adsa.jpg"
          },...
    

    对上面的 Json Response 像这样尝试

     public class ItemListModel {
         public ArrayList<Result> results;
    
        @Override
        public String toString() {
            return "Response [results=" + results + "]";
        }
    
        public ArrayList<Result> getResults() {
            return results;
        }
    
    }
    

    那么

        public class Result {
    
        private String user_id;
        private String item_id;
        private String name;
        private String price;
        private String description;
        private String created_at;
        private ThumbnailModel thumbnail; 
        public String getUser_id() {
            return user_id;
        }
    
        public String getItem_id() {
            return item_id;
        }
    
        public String getName() {
            return name;
        }
    
        public String getPrice() {
            return price;
        }
    
        public String getDescription() {
            return description;
        }
    
        public String getCreated_at() {
            return created_at;
        }
    
        public ThumbnailModel getThumbnail() {
            return thumbnail;
        }
    
        @Override
        public String toString() {
            return "Result [user_id=" + user_id + ", item_id=" + item_id
                    + ", name=" + name + ", price=" + price + ", description="
                    + description + ", created_at=" + created_at + ", thumbnail="
                    + thumbnail + "]";
        }
    
    }
    

    最后

    public class ThumbnailModel {
    private String image50;
    private String image100;
    public String getImage50() {
        return image50;
    }
    public String getImage100() {
        return image100;
    }
    @Override
    public String toString() {
        return "ThumbnailModel [image50=" + image50 + ", image100=" + image100
                + "]";
    }
    

    }

    这是上述 Json 的正确模型。

    编辑:-

    private Response.Listener<ItemListModel> createMyReqSuccessListener() {
            return new Response.Listener<ItemListModel>() {
                @Override
                public void onResponse(ItemListModel response) {
                    try {
                        Log.d("Name> ", response.getResults().get(0).getName());//Edited
                        Log.d("ThumbnailModel Image> ", response.getResults().get(0).getThumbnail().getImage100());//Edited
                        pd.dismiss();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                };
        };
    }
    

    希望这对你有用。

    【讨论】:

    • 嘿,您的解决方案有效。但是如何从ResultThumbnailModel 类中获取字符串值?
    • @AimanB 如果可行,请不要忘记投票并接受答案。
    • @AimanBI 添加了获取 Result 和 ThumbnailModel 类的代码。再次检查我的答案。
    • @AmitGupta 你的 ThumbnailModel 类已经过时,简单的Map&lt;String, Strig&gt; 会更好
    猜你喜欢
    • 2012-06-22
    • 2012-05-28
    • 2014-12-05
    • 2021-07-07
    • 2013-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    相关资源
    最近更新 更多