当前位置: 首页 > 面试题库 >

如何使用Jackson制作POJO和解析递归对象?

华甫
2023-03-14
问题内容

我从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是一个可以具有多个postingjson对象的JSON数组。现在categories也是JSON数组。现在棘手的部分是,我可以parentCategory在每个类别对象中拥有多个级别,并且我不知道parentCategory我将拥有多少个级别。给定以上JSON,我需要提取taskid每个类别和taskIdlast的内容parentCategory。所以应该是这样的:

79720=10987
12980=78765

其中79720是类别10987的taskId,是last的taskId parentCategory。其他人也一样。

以下是我的代码,其中通过进行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。由于我可以拥有不知道的嵌套级别的parentCategory。

使用Jackson可以做到吗?

这是为Category和生成的POJO类ParentCategory。我不确定是否需要在此处进行任何更改以便解析递归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>();

  ...

}

问题答案:

这次我将与GSon接触

可以更轻松地管理递归。

可以从json2pojo网站创建Pojo,只需选择GSon作为JSon库即可。

这些是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;
    }

}

因此,这是一个测试实现:

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

也许仍然需要一些调整,但是您明白了。

希望能帮助到你!

编辑:作为操作要求,我添加了杰克逊版本。

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


 类似资料:
  • 问题内容: 我试图简化我的代码:我想存储键和值(所有字符串)。 我实际上是使用A 来存储它。hat方法可以是值()或新节点()。 如何简化此代码?递归函数会很好。 问题答案: 假设您的最终目标只是将JSON反序列化为,那么使用Jackson可以简单得多。使用: 您将需要错误处理等,但这是一个很好的起点。

  • 我试图简化我的代码:我想存储键和值(所有字符串)。 我实际上在使用

  • 我需要使用Gson将传入的json消息解析为Java对象。类“MessageBody”应该用于向Gson提供信息。fromJson(json,MessageBody.class); json消息如下所示。 第一层有三个静态字段。第三个字段(“字段”)是“数据字段”对象的列表。 DataField对象有一个类型字段和一个值字段。它的价值可以是异质的。预期类型为:“字符串”、“int”、“布尔”和“H

  • 您好,我不熟悉JSON学习,并尝试将上述JSON解析为POJO对象。”https://api.apis.guru/v2/list.json“。我无法理解如何存储不同的主机名”1 Forge。com”,“1密码。local:connect“作为java类中的一个字段。上面的任何帮助都会对我很有帮助

  • 我在通过邮递员传递json数据时遇到问题。如果Mandetory日期带有注释,没问题。另一个日期接受null。但是在更新时,该日期会产生问题。我使用Java1.8与Spring启动 以下链接我已经访问过,但不适合这个。杰克逊JSON解析错误的LocalDateTime解析:无法构造java.time.LocalDate的实例:没有String参数构造函数/工厂方法从String值反序列化https

  • 本文向大家介绍js使用递归解析xml,包括了js使用递归解析xml的使用技巧和注意事项,需要的朋友参考一下 xml结构: 解析方法: 以上就是javascript使用递归解析XML的全部代码了,超级简洁,非常使用,给需要的小伙伴参考下。