如何仅使用Jackson序列化孩子的ID [英] How to serialize only the ID of a child with Jackson
问题描述
使用Jackson(fasterxml.jackson 2.1.1)时是否有内置方法只能序列化孩子的id?我们想通过REST发送订单
,其中包含 Person
参考。然而,person对象非常复杂,我们可以在服务器端刷新它,所以我们只需要主键。
Is there a built-in way to only serialize the id of a child when using Jackson (fasterxml.jackson 2.1.1)? We want to send an Order
via REST which has a Person
reference. The person object however is quite complex and we could refresh it on the server side, so all we need is the primary key.
或者我需要一个自定义序列化程序?或者我需要 @JsonIgnore
所有其他属性?这会阻止在请求订单
对象时发回 Person
数据吗?我不确定我是否需要它,但如果可能的话我想控制它...
Or do I need a custom serializer for this? Or do I need to @JsonIgnore
all other properties? Would that prevent the Person
data from being sent back when requesting an Order
object? I'm not sure yet if I'll need that but I'd like to have control over it if possible...
推荐答案
有几种方法。第一个是使用 @JsonIgnoreProperties
从子项中删除属性,如下所示:
There are couple of ways. First one is to use @JsonIgnoreProperties
to remove properties from a child, like so:
public class Parent {
@JsonIgnoreProperties({"name", "description" }) // leave "id" and whatever child has
public Child child; // or use for getter or setter
}
另一种可能性,如果Child对象总是序列化为id:
another possibility, if Child object is always serialized as 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。
which would also work for serialization, and ignore properties other than id. Result would not be wrapped as Object however.
这篇关于如何仅使用Jackson序列化孩子的ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!