代码之家  ›  专栏  ›  技术社区  ›  user1950349

如何使用jackson生成POJO和解析递归对象?

  •  -1
  • user1950349  · 技术社区  · 7 年前

    我有一个从rest服务返回的低于JSON的响应。现在,我需要将下面的JSON响应反序列化为POJO。我和杰克逊一起工作。

    {
        "pagination": {
            "number": 1,
            "entriesPerPage": 200,
            "total": 3
        },
        "postings": [{
            "categories": [{
            "taskid": "79720",
            "name": "Sunglasses",
            "parentCategory": {
                "taskid": "394",
                "name": "Sunglasses & Fashion Eyewear",
                "parentCategory": {
                    "taskid": "2340",
                    "name": "Men's Accessories",
                    "parentCategory": {
                        "taskid": "10987",
                        "name": "Clothing, Shoes & Accessories"
                    }
                }
            }
        }]
    },
    {
        "categories": [{
            "taskid": "12980",
            "name": "Toys",
            "parentCategory": {
                "taskid": "123",
                "name": "Fashion",
                "parentCategory": {
                    "taskid": "78765",
                    "name": "Men's Accessories"
                }
            }
        }]
    }],
        "total": 2
    }
    

    在上面的json中, postings 是一个JSON数组,可以有多个 posting json对象。现在 categories 也是JSON数组。现在棘手的是我可以有多个层次的 parentCategory 在每个类别对象中,我不知道 父类别 我会的。给出上面的JSON,我需要提取 taskid 每个类别的 taskId 最后一个的 父类别 . 所以应该是这样的:

    79720=10987
    12980=78765
    

    哪里 79720 是类别的taskId,并且 10987 是上一个的taskId 父类别 . 另一个也一样。

    下面是我的代码,我正在通过http调用将JSON反序列化到POJO中:

    ResponseEntity<Stuff> responseEntity = HttpClient.getInstance().getClient()
        .exchange(URI.create(endpoint), HttpMethod.POST, requestEntity, Stuff.class);
    Stuff response = responseEntity.getBody();
    
    List<Posting> postings = response.getPostings();
    for(Posting postings : postings) {
        //....
    }
    

    我的困惑是——如何为上述JSON生成POJO?我试过使用 jsonschema2pojo 但这不是为 父类别 . 因为我可以有parentCategory的嵌套级别,这是我之前不知道的。

    使用Jackson可以做到这一点吗?

    这是为生成的POJO类 Category ParentCategory . 我不确定是否需要在这里进行任何更改,以便可以解析递归 父类别 对象

    @JsonInclude(JsonInclude.Include.NON_NULL)
    @JsonPropertyOrder({"taskid", "name", "parentCategory"})
    public class Category {
      @JsonProperty("taskid")
      private String taskid;
      @JsonProperty("name")
      private String name;
      @JsonProperty("parentCategory")
      private ParentCategory parentCategory;
      @JsonIgnore
      private Map<String, Object> additionalProperties = new HashMap<String, Object>();
    
      ...
    
    }
    
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @JsonPropertyOrder({"taskid", "name", "parentCategory"})
    public class ParentCategory {
      @JsonProperty("taskid")
      private String taskid;
      @JsonProperty("name")
      private String name;
      @JsonProperty("parentCategory")
      private ParentCategory parentCategory;
      @JsonIgnore
      private Map<String, Object> additionalProperties = new HashMap<String, Object>();
    
      ...
    
    }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Black.Jack    7 年前

    这次我会 GSon

    它以较少的工作量管理递归。

    只需选择GSon作为JSon库,就可以从json2pojo网站制作pojo。

    以下是POJO:

    import java.io.Serializable;
    
    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;
    
    public class Pagination implements Serializable
    {
    
        public Pagination() {
            super();
            // TODO Auto-generated constructor stub
        }
    
        @SerializedName("number")
        @Expose
        private Integer number;
        @SerializedName("entriesPerPage")
        @Expose
        private Integer entriesPerPage;
        @SerializedName("total")
        @Expose
        private Integer total;
        private final static long serialVersionUID = 5114620434202813556L;
    
        public Integer getNumber() {
            return number;
        }
    
        public void setNumber(Integer number) {
            this.number = number;
        }
    
        public Integer getEntriesPerPage() {
            return entriesPerPage;
        }
    
        public void setEntriesPerPage(Integer entriesPerPage) {
            this.entriesPerPage = entriesPerPage;
        }
    
        public Integer getTotal() {
            return total;
        }
    
        public void setTotal(Integer total) {
            this.total = total;
        }
    
    }
    
    
    
    import java.io.Serializable;
    import java.util.List;
    
    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;
    
    public class Categories implements Serializable
    {
    
        public Categories() {
            super();
            // TODO Auto-generated constructor stub
        }
    
        @SerializedName("pagination")
        @Expose
        private Pagination pagination;
        @SerializedName("postings")
        @Expose
        private List<Posting> postings = null;
        @SerializedName("total")
        @Expose
        private Integer total;
        private final static long serialVersionUID = 4589512697836725240L;
    
        public Pagination getPagination() {
            return pagination;
        }
    
        public void setPagination(Pagination pagination) {
            this.pagination = pagination;
        }
    
        public List<Posting> getPostings() {
            return postings;
        }
    
        public void setPostings(List<Posting> postings) {
            this.postings = postings;
        }
    
        public Integer getTotal() {
            return total;
        }
    
        public void setTotal(Integer total) {
            this.total = total;
        }
    
    }
    
    
    import java.io.Serializable;
    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;
    
    public class Category implements Serializable
    {
    
        public Category() {
            super();
            // TODO Auto-generated constructor stub
        }
    
        @SerializedName("taskid")
        @Expose
        private String taskid;
        @SerializedName("name")
        @Expose
        private String name;
        @SerializedName("parentCategory")
        @Expose
        private ParentCategory parentCategory;
        private final static long serialVersionUID = -2127963072268572959L;
    
        public String getTaskid() {
            return taskid;
        }
    
        public void setTaskid(String taskid) {
            this.taskid = taskid;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public ParentCategory getParentCategory() {
            return parentCategory;
        }
    
        public void setParentCategory(ParentCategory parentCategory) {
            this.parentCategory = parentCategory;
        }
    
    }
    
    
    import java.io.Serializable;
    import java.util.List;
    
    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;
    
    public class Posting implements Serializable
    {
    
        @SerializedName("categories")
        @Expose
        private List<Category> categories = null;
        private final static long serialVersionUID = 8135185675909461065L;
    
        public List<Category> getCategories() {
            return categories;
        }
    
        public Posting() {
            super();
            // TODO Auto-generated constructor stub
        }
    
        public void setCategories(List<Category> categories) {
            this.categories = categories;
        }
    
    }
    
    
    import java.io.Serializable;
    import java.util.List;
    
    import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;
    
    public class ParentCategory implements Serializable
    {
    
        @SerializedName("taskid")
        @Expose
        private String taskid;
        @SerializedName("name")
        @Expose
        private String name;
        @SerializedName("parentCategory")
        @Expose
        private List<ParentCategory>  parentCategory;
    
    
        public ParentCategory() {
            super();
            // TODO Auto-generated constructor stub
        }
    
        private final static long serialVersionUID = -5989749742502713615L;
    
        public String getTaskid() {
            return taskid;
        }
    
        public void setTaskid(String taskid) {
            this.taskid = taskid;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public List<ParentCategory> getParentCategory() {
            return parentCategory;
        }
    
        public void setParentCategory(List<ParentCategory> parentCategory) {
            this.parentCategory = parentCategory;
        }
    
    }
    

    这是一个测试实现:

     Pagination pagination = new Pagination();
    
             pagination.setNumber(1);
             pagination.setEntriesPerPage(200);
             pagination.setTotal(3);
    
             Categories categories = new Categories(); 
             categories.setPagination(pagination);
    
             Category category = new Category();
             category.setName("Sunglasses");
             category.setTaskid("79720");
    
             List<Category> categoryList = new ArrayList<Category>();
    
             Posting posting = new Posting(); 
             posting.setCategories(categoryList);
    
             List<ParentCategory> parentCategoryList = new ArrayList<ParentCategory>();
             List<ParentCategory> parentCategoryList2 = new ArrayList<ParentCategory>();
    
             ParentCategory  parentCategory1 = new ParentCategory(); 
             parentCategory1.setName("Sunglasses & Fashion Eyewear");
             parentCategory1.setTaskid("394");
    
             ParentCategory  parentCategory2 = new ParentCategory(); 
             parentCategory2.setName("Men's Accessories");
             parentCategory2.setTaskid("2340");
    
             ParentCategory  parentCategory3 = new ParentCategory(); 
             parentCategory3.setName("Clothing, Shoes & Accessories");
             parentCategory3.setTaskid("10987");
    
             parentCategoryList.add(parentCategory2); 
             parentCategoryList2.add(parentCategory3);
              parentCategory2.setParentCategory(parentCategoryList2);
             parentCategory1.setParentCategory(parentCategoryList);
             category.setParentCategory(parentCategory1);
    
              Gson gson = new Gson();
                System.out.println(gson.toJson(category));
    

    ...这是生成的Json:

    {
        "taskid": "79720",
        "name": "Sunglasses",
        "parentCategory": {
            "taskid": "394",
            "name": "Sunglasses \u0026 Fashion Eyewear",
            "parentCategory": [{
                "taskid": "2340",
                "name": "Men\u0027s Accessories",
                "parentCategory": [{
                    "taskid": "10987",
                    "name": "Clothing, Shoes \u0026 Accessories"
                }]
            }]
        }
    }
    

    也许还需要一些调整,但你已经有了主意。

    希望有帮助!

    编辑:根据op的要求,我添加了Jackson版本。

    POJO:

    import java.io.Serializable;
    
    import com.fasterxml.jackson.annotation.JsonInclude;
    import com.fasterxml.jackson.annotation.JsonProperty;
    import com.fasterxml.jackson.annotation.JsonPropertyOrder;
    
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @JsonPropertyOrder({"taskid", "name", "parentCategory"})
    public class ParentCategory implements Serializable{
        /**
         * 
         */
        private static final long serialVersionUID = 1L;
        @JsonProperty("taskid")
        private String taskid;
        @JsonProperty("name")
        private String name;
        @JsonProperty("parentCategory")
        private ParentCategory parentCategory;
        public String getTaskid() {
            return taskid;
        }
        public void setTaskid(String taskid) {
            this.taskid = taskid;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public ParentCategory getParentCategory() {
            return parentCategory;
        }
        public void setParentCategory(ParentCategory parentCategory) {
            this.parentCategory = parentCategory;
        }
    
    
    }
    
    
    import com.fasterxml.jackson.annotation.JsonInclude;
    import com.fasterxml.jackson.annotation.JsonProperty;
    import com.fasterxml.jackson.annotation.JsonPropertyOrder;
    
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @JsonPropertyOrder({"taskid", "name", "parentCategory"})
    public class Category implements Serializable{
        /**
         * 
         */
        private static final long serialVersionUID = 1L;
        @JsonProperty("taskid")
        private String taskid;
        @JsonProperty("name")
        private String name;
        @JsonProperty("parentCategory")
        private ParentCategory parentCategory;
    
        public String getTaskid() {
            return taskid;
        }
        public void setTaskid(String taskid) {
            this.taskid = taskid;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public ParentCategory getParentCategory() {
            return parentCategory;
        }
        public void setParentCategory(ParentCategory parentCategory) {
            this.parentCategory = parentCategory;
        }
    
    
    
    }
    
    
    public class Test {
    
    
        public static void main(String[] args) throws JsonProcessingException {
    
    
             Category category = new Category();
             category.setName("Sunglasses");
             category.setTaskid("79720");
    
             List<Category> categoryList = new ArrayList<Category>();
    
             List<ParentCategory> parentCategoryList = new ArrayList<ParentCategory>();
             List<ParentCategory> parentCategoryList2 = new ArrayList<ParentCategory>();
    
             ParentCategory  parentCategory1 = new ParentCategory(); 
             parentCategory1.setName("Sunglasses & Fashion Eyewear");
             parentCategory1.setTaskid("394");
    
             ParentCategory  parentCategory2 = new ParentCategory(); 
             parentCategory2.setName("Men's Accessories");
             parentCategory2.setTaskid("2340");
    
             ParentCategory  parentCategory3 = new ParentCategory(); 
             parentCategory3.setName("Clothing, Shoes & Accessories");
             parentCategory3.setTaskid("10987");
    
             parentCategory1.setParentCategory(parentCategory2);
             parentCategory2.setParentCategory(parentCategory3);
             category.setParentCategory(parentCategory1);
    
            ObjectMapper objectMapper = new ObjectMapper();
    
            String testJson = objectMapper.writeValueAsString(category);
            System.out.println(testJson);
        }
    
    }
    

    这里还有一个测试结果:

    {
        "taskid": "79720",
        "name": "Sunglasses",
        "parentCategory": {
            "taskid": "394",
            "name": "Sunglasses & Fashion Eyewear",
            "parentCategory": {
                "taskid": "2340",
                "name": "Men's Accessories",
                "parentCategory": {
                    "taskid": "10987",
                    "name": "Clothing, Shoes & Accessories"
                }
            }
        }
    }