问题
Almost the same question but the accepted answer does not fit the general need. Having Simple class and custom serializer like:
Example class
@Getter
@Setter
public class ExampleClass {
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonSerialize(using = StringSerializer.class)
private String stringNull;
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonSerialize(using = StringSerializer.class)
private String stringOk = "ok";
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonSerialize(converter = StringSerializer.class)
private String stringNotOk = "notOk";
}
Custom serializer
@SuppressWarnings("serial")
public static class StringSerializer extends StdSerializer<String> {
public StringSerializer() {
super(String.class);
}
@Override
public void serialize(String value, JsonGenerator gen, SerializerProvider serializers)
throws IOException {
if(value != null && value.equals("ok")) {
gen.writeString(value);
}
}
}
So I only want to print out elements that are equal to "ok" but if not equal to "ok" I do not want to print anything. Works fine except for stringNotOk
. When calling ObjectMappper like:
new ObjectMapper().writeValueAsString(new ExampleClass());
it produces "bad" JSON:
{"stringOk":"ok","stringNotOk"}
Is there any other way or can I can avoid to raise the serializer to class level and create it separately for each class having such field na taking account field name etc...?
Can I - for example - somehow "revert" back and remove the name "stringNotOk" from already written JSON?
How could this be made in a generic way so that just one serializer and an annotation on needed fields were used?
回答1:
I think you are looking for something like
@JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = OkFilter.class)
public class OkFilter {
@Override
public boolean equals(Object obj) {
//your logic for finding 'ok' value here
}
}
Here you can read more about this https://www.logicbig.com/tutorials/misc/jackson/json-include-customized.html
来源:https://stackoverflow.com/questions/62542799/how-to-ignore-field-totally-by-its-value-when-serializing-with-jackson-with-anno