本文介绍了使Jackson序列化程序覆盖特定的忽略字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有像这样的杰克逊注释类:
I have Jackson annotated class like this :
public class MyClass {
String field1;
@JsonIgnore
String field2;
String field3;
@JsonIgnore
String field4;
}
假设我不能更改MyClass代码.然后,如何使ObjectMapper仅覆盖field2的JsonIgnore并将其序列化为json?我希望它忽略field4.这是简单的几行代码吗?
Assume that I cannot change MyClass code. Then, how can I make ObjectMapper override the JsonIgnore for field2 only and serialize it to json ? I want it to ignore field4 though. Is this easy and few lines of code ?
我的常规序列化代码:
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"
}
这篇关于使Jackson序列化程序覆盖特定的忽略字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!