在使用 Jackson (fasterxml.jackson 2.1.1) 时,是否有一种仅序列化 child id 的内置方法?我们想通过具有 Person
引用的 REST 发送一个 Order
。但是 person 对象非常复杂,我们可以在服务器端刷新它,所以我们只需要主键。
或者我需要一个自定义序列化器吗?还是我需要 @JsonIgnore
所有其他属性?在请求 Order
对象时,这会阻止 Person
数据被发回吗?我还不确定我是否需要它,但如果可能的话,我想控制它......
最佳答案
有几种方法。第一个是使用 @JsonIgnoreProperties
来移除子元素的属性,如下所示:
public class Parent {
@JsonIgnoreProperties({"name", "description" }) // leave "id" and whatever child has
public Child child; // or use for getter or setter
}
另一种可能性,如果子对象总是序列化为 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 以外的属性。但是,结果不会被包装为 Object。
关于java - 如何仅序列化 Jackson 的 child 的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17542240/