我有一个对象,我希望我的 jackson 对其进行序列化。例如:
public class RaceCar {
public String model;
public Int topSpeed;
}
我的困难是我不希望我的 RaceCar 的所有字段都被序列化。我试图将我的对象转换为一个父类(super class),该父类(super class)无法访问我想要隐藏的字段。例如:
public class Car {
public String model;
}
然而,尽管有 Actor 阵容, jackson 仍然设法连载了我的 RaceCar 的所有字段。输出将是:
{"model": "x103", "topSpeed": 200}
即使 RaceCar 对象被转换为 Object,Jackson 也会序列化我的 RaceCar 的所有字段。我猜测 jackson 使用某种反射机制来绕过我的 Actor 阵容。有什么办法可以阻止 jackson 绕过我的 Actor 阵容吗?
编辑:我应该指定不能使用@JsonIgnore,因为在某些情况下我想返回整个对象,而在其他情况下,我想返回具有较少字段的对象。
最佳答案
MixIn 就是您所需要的:
Q38034525.java
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Q38034525
{
public static void main(String[] args) throws Exception
{
final RaceCar rc = new RaceCar();
rc.model = "Corvette Stringray";
rc.topSpeed = 195;
final ObjectMapper om = new ObjectMapper();
System.out.println(om.writeValueAsString(rc));
final ObjectMapper om2 = om.copy().addMixIn(RaceCar.class, RestrictedRaceCar.class);
System.out.println(om2.writeValueAsString(rc));
}
public static abstract class RestrictedRaceCar
{
@JsonIgnore
public Integer topSpeed;
}
public static class RaceCar
{
public String model;
public Integer topSpeed;
}
}
输出:
{"model":"Corvette Stringray","topSpeed":195}
{"model":"Corvette Stringray"}
注意:
You must
.copy()
or create a new instance ofObjectMapper
as they are immutable and just doing.addMixIn()
on the instance will not modify it.
关于java - 如何防止 jackson 绕过类型转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38034525/