繁体   English   中英

Android-将此JSON反序列化为POJO

[英]Android - Deserialize this JSON to a POJO

这是我的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"
      },...

我在执行反序列化吗?

public class ItemListModel {

    private String user_id;
    private String item_id;
    private String name;
    private String price;
    private String category;
    private ArrayList<ThumbnailResponse> thumbnail;

    public ItemListModel(){}

    // getters
}

public class ThumbnailResponse {
    private String image50;
    private String image100;

    public ThumbnailResponse(){     
    }

    //getters
 }

我只是感到困惑,我们什么时候在JSON文件中将ArrayList,Array或List用于数组或对象?

还有一件事,如果是这种情况,我是否还需要将results作为数组生成?

如你所给

"thumbnail": {
        "image50": "http://www.example.com/adsa.jpg",
        "image100": "hhttp://www.example.com/adsa.jpg"
      }

不是JsonArray。 因此,您无需将ThumbnailResponse用作ItemListModelArrayList

您的模型应该是

public class ItemListModel {

    private String user_id;
    private String item_id;
    private String name;
    private String price;
    private String category;
    private ThumbnailResponse thumbnail; // Not array List

    public ItemListModel(){}

    // getters
}

还有一件事,如果是这种情况,我是否还需要将结果作为数组生成?

您的主数据容器应包含ItemListModel ArrayList。 像下面

ArrayList<ItemListModel> results = new ArrayList<ItemListModel>(); 
  • []在json->数组中
  • {}在json->对象或地图中

在你的情况下

// change
private ArrayList<ThumbnailResponse> thumbnail;
// to
private Map<String,String> thumbnail;

如果您希望以声明Java对象的方式进行操作,则需要提供一个转换器(取决于您使用的框架)

 List<ItemListModel > ItemListModel ;

         try {

        Type listType = new TypeToken<List<ItemListModel >>(){}.getType();

        result= (List<ItemListModel >) gson.fromJson(result, listType);

    } catch (Exception e) {
        Log.e("Parsing exeption", e.getLocalizedMessage(), e);

    }
this should work

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM