小编典典

如何只序列化Jackson子的ID

json

在使用Jackson(fasterxml.jackson
2.1.1)时,是否有内置的方式仅序列化子的ID?我们要发送一个Order通过REST的Person参考文件。但是person对象非常复杂,我们可以在服务器端刷新它,因此我们需要的只是主键。

还是我需要一个定制的序列化器?还是我需要@JsonIgnore其他所有属性?这样可以防止Person在请求Order对象时将数据发送回去吗?我不确定是否需要,但我想尽可能控制它。


阅读 343

收藏
2020-07-27

共1个答案

小编典典

有几种方法。第一个是使用@JsonIgnoreProperties来删除子级的属性,如下所示:

public class Parent {
   @JsonIgnoreProperties({"name", "description" }) // leave "id" and whatever child has
   public Child child; // or use for getter or setter
}

另一种可能性,如果Child对象始终被序列化为id:

public class Child {
    // use value of this property _instead_ of object
    @JsonValue
    public int id;
}

还有一种方法是使用 @JsonIdentityInfo

public class Parent {
   @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, property="id")
   @JsonIdentityReference(alwaysAsId=true) // otherwise first ref as POJO, others as id
   public Child child; // or use for getter or setter

   // if using 'PropertyGenerator', need to have id as property -- not the only choice
   public int id;
}

这也适用于序列化,并忽略id以外的属性。结果不会包装为对象。

2020-07-27