如何使用jackson制作POJO并解析递归对象? [英] How to make POJO and parse recursive objects using jackson?

查看:83
本文介绍了如何使用jackson制作POJO并解析递归对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个以下JSON响应,我从休息服务回来。现在我需要将JSON响应下面的反序列化反转为POJO。我正在和杰克逊合作。

I have a below JSON response that I am getting back from a rest service. Now I need to deserialize below JSON response into a POJO. I am working with Jackson.

{
    "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中,发布是一个JSON数组,可以有多个发布 json对象。现在类别也是JSON数组。现在棘手的部分是我可以在每个类别对象中有多个级别的 parentCategory ,我不知道有多少级别的 parentCategory 我会的。给出以上JSON,我需要提取每个类别的 taskid taskId 的最后 parentCategory 。所以它应该是这样的:

In above json, postings is a JSON array which can have multiple posting json object. Now categories is also JSON array. Now tricky part is I can have multiple levels of parentCategory inside each category object and I don't know how many levels of parentCategory I will have. Give above JSON, I need to extract taskid of each category and taskId of last parentCategory. So it should be like this:

79720=10987
12980=78765

其中 79720 是类别的taskId而 10987 是最后 parentCategory 的taskId。与其他人类似。

Where 79720 is taskId of category and 10987 is the taskId of last parentCategory. Similarly for other one.

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

Below is my code where I am deserializing JSON into my POJO by making an http call:

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 。因为我可以拥有嵌套级别的parentCategory,这是我手头不知道的。

Confusion I have is - How to make POJO for above JSON? I tried using jsonschema2pojo but it's not making right classes for parentCategory. Since I can have nested levels of parentCategory which I don't know before hand.

使用Jackson可以做到吗?

Is this possible to do using Jackson?

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

This is the POJO class generated for Category and ParentCategory. I am not sure whether I need to make any changes here so that I can parse recursive parentCategory object.

@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>();

  ...

}


推荐答案

这次我将使用 GSon

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

Which manages recursion with less effort.

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

Pojos can be made from json2pojo website, simply choosing GSon as JSon library.

这些是Pojos:

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;
    }

}

所以这是一个测试实现:

So this is a test implementation:

 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:

...and this is the resulting 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"
            }]
        }]
    }
}

也许还需要一些调整,但你明白了。

Maybe still need a bit of tweaking but you got the idea.

希望有所帮助!

编辑:正如操作要求我添加杰克逊版本。

as the op requests I add the Jackson Version.

Pojos:

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"
            }
        }
    }
}

这篇关于如何使用jackson制作POJO并解析递归对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆