忽略杰克逊序列化的特定字段
我正在使用杰克逊图书馆。
我想在序列化/反序列化时忽略特定字段,因此例如:
public static class Foo {
public String foo = "a";
public String bar = "b";
@JsonIgnore
public String foobar = "c";
}
应该给我:
{
foo: "a",
bar: "b",
}
但我得到:
{
foo: "a",
bar: "b",
foobar: "c"
}
我正在使用以下代码序列化对象:
ObjectMapper mapper = new ObjectMapper();
String out = mapper.writeValueAsString(new Foo());
我的类中字段的真实类型是Log4J 记录器类。我做错了什么?
I'm using the Jackson library.
I want to ignore a specific field when serializing/deserializing, so for example:
public static class Foo {
public String foo = "a";
public String bar = "b";
@JsonIgnore
public String foobar = "c";
}
Should give me:
{
foo: "a",
bar: "b",
}
But I'm getting:
{
foo: "a",
bar: "b",
foobar: "c"
}
I'm serializing the object with this code:
ObjectMapper mapper = new ObjectMapper();
String out = mapper.writeValueAsString(new Foo());
The real type of the field on my class is an instance of the Log4J Logger class. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
好吧,由于某种原因,我错过了这个答案。
以下代码按预期工作:
Ok, so for some reason I missed this answer.
The following code works as expected:
另外值得注意的是,此解决方案使用 DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES: https://stackoverflow.com/a/18850479/1256179
Also worth noting is this solution using DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES: https://stackoverflow.com/a/18850479/1256179
参考我如何告诉 Jackson 忽略我无法控制源代码的属性?
您可以使用 Jackson Mixins。例如:
使用这个 Mixin
使用这个:
Reference from How can I tell jackson to ignore a property for which I don't have control over the source code?
You can use Jackson Mixins. For example:
With this Mixin
With this:
尝试忽略 get 方法,而使用 set 方法。例如
在我的测试用例中工作。
这个想法是反序列化器可以写入该值,但序列化器不应该看到该值。
try to ignore the get method, and use the set method. e.g.
Worked in my test case.
The idea is the deserializer can write the value, but the serializer should not see the value.