java - 让 Jackson 序列化程序覆盖特定的忽略字段
问题描述
我有杰克逊这样的注释类:
public class MyClass {
String field1;
@JsonIgnore
String field2;
String field3;
@JsonIgnore
String field4;
}
假设我无法更改 MyClass 代码。那么,如何让 ObjectMapper 仅覆盖 field2 的 JsonIgnore 并将其序列化为 json ?我希望它忽略 field4。这是简单的几行代码吗?
我的常规序列化代码:
public String toJson(SomeObject obj){
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = null;
try {
json = ow.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return json;
}
解决方案
您可以使用MixIn
功能:
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class JsonApp {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.addMixIn(MyClass.class, MyClassMixIn.class);
System.out.println(mapper.writeValueAsString(new MyClass()));
}
}
interface MyClassMixIn {
@JsonProperty
String getField2();
}
上面的代码打印:
{
"field1" : "F1",
"field2" : "F2",
"field3" : "F3"
}
推荐阅读
- java - Ksoap2 预期 XmlPullParserException
- python - 如何在熊猫中将行块合并为单行?
- angularjs - 使用 Angular Gettext 翻译 JSON 文件
- r - 由 gpoup 分隔的多重插补
- javascript - Laravel Echo 和 JQuery
- angular - 如何使用/启用动画图标?
- css - 浮动 - 垂直堆叠,忽略前一行的最高高度?
- android - RecyclerView Adapter 位置改变视图大小和可见性的问题
- sql - 从 ASE 中的另一个会话中查询“COMPATIBILITY_MODE”ON/OFF 的状态
- javascript - 在 div 中显示 A4 pdf 响应 HTML/CSS