如何在 Spring Boot ObjectMapper 中排除带有自定义注释的字段
我需要在应用程序中拥有两个不同的ObjectMapper
。
我正在使用的 Pojo:
public class Student {
private String name;
private Integer age;
@HideThisField
private String grade;
// getters & setters..
}
一个是基于开箱即用的配置的 ObjectMapper
,如下所示:
@Bean("objectMapper")
public ObjectMapper getRegularObjectMapper() {
//With some configurations
return new ObjectMapper();
}
我需要另一个 ObjectMapper
,它在序列化时会忽略基于字段上的注释。
@Bean("customObjectMapper")
public ObjectMapper getCustomObjectMapper() {
// This is where i want to ignore the fields with @HideThisField
return new ObjectMapper();
}
两个映射器的输出:
objectMapper.writeValuesAsString(someStudent)
打印:
{"name": ""student1", 年龄: 10, "grade": "A+"}
customObjectMapper.writeValuesAsString(someStudent)
打印:
{"name": ""student1", 年龄: 10}
I have a need to have two different ObjectMapper
in the application.
Pojo I am working with:
public class Student {
private String name;
private Integer age;
@HideThisField
private String grade;
// getters & setters..
}
One is the out of the box configuration based ObjectMapper
as below:
@Bean("objectMapper")
public ObjectMapper getRegularObjectMapper() {
//With some configurations
return new ObjectMapper();
}
I need another ObjectMapper
that while serializing ignores a few fields for all objects based on an annotation on a field.
@Bean("customObjectMapper")
public ObjectMapper getCustomObjectMapper() {
// This is where i want to ignore the fields with @HideThisField
return new ObjectMapper();
}
Output of the two mappers:
objectMapper.writeValuesAsString(someStudent)
prints:
{"name": ""student1", age: 10, "grade": "A+"}
customObjectMapper.writeValuesAsString(someStudent)
prints:
{"name": ""student1", age: 10}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
JacksonAnnotationIntrospector
处理标准Jackson
注释。重写hasIgnoreMarker
方法,你可以让它根据你自己的注释工作。控制台输出为:
getCustomObjectMapper()
不要跳过JsonIgnore
注释,因为您覆盖了标准,如果需要,您需要将其添加到 if 块中.JacksonAnnotationIntrospector
handles standardJackson
annotations. Overriding thehasIgnoreMarker
method, you can make it work according to your own annotation.The console output is:
getCustomObjectMapper()
don't skipsJsonIgnore
annotations because you override the standard, if you want, you need to add this to the if block.