您可以使用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"
}
,
您可以像这样使用自定义序列化程序(我将重构交给您):
private String getJson(final MyClass obj) {
final ObjectMapper om = new ObjectMapper();
om.registerModule(new SimpleModule(
"CustomModule",Version.unknownVersion(),Collections.emptyMap(),Collections.singletonList(new StdSerializer<MyClass>(MyClass.class) {
@Override
public void serialize(final MyClass value,final JsonGenerator jgen,final SerializerProvider provider) throws IOException {
jgen.writeStartObject();
jgen.writeStringField("field1",value.field1);
jgen.writeStringField("field2",value.field2);
jgen.writeStringField("field3",value.field3);
jgen.writeEndObject();
}
})));
try {
return om.writeValueAsString(obj);
} catch (final JsonProcessingException e) {
throw new RuntimeException(e);
}
}
您可以在google / stackoverflow上找到有关自定义序列化程序的更多信息,我想我回答了类似的问题here
本文链接:https://www.f2er.com/3139218.html