I'm currently using Jackson to serialize a big class in my program, but I can't seem to find how to ignore/skip specific classes from being serialized. I've tried using the annotation @JsonIgnoreType like it was recommended here, but that only seems to work for actual fields (not entries in a list). I've also tried tagging the classes I want to ignore with @JsonIgnoreType and using a custom annotation introspector, but it just saves the empty classes without the fields (except for className):
saveMapper.setAnnotationIntrospector(new JacksonAnnotationIntrospector() {
@Override
public boolean hasIgnoreMarker(AnnotatedMember m) {
return super.hasIgnoreMarker(m) || m.getDeclaringClass().getAnnotation(JsonIgnoreType.class) != null;
}
});
...
@JsonIgnoreType
private static class ScriptA extends Script {
private int dontKeep;
public ScriptA() {
dontKeep = 25;
}
}
Result:
{
"scripts" : [ {
"className" : "com.JsonExemple$ScriptA"
}, {
"className" : "com.JsonExemple$ScriptB",
"keep" : 50
} ]
}
Here's the snippet:
package com;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import com.fasterxml.jackson.databind.SerializationFeature;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* @author clem585
* @created 28/02/2021 - 1:43 AM
*/
public class JsonExemple {
public static void main(String[] args) {
try {
// create Jackson JSON writer
ObjectMapper saveMapper = new ObjectMapper()
.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
ObjectWriter saveWriter = saveMapper.writer().withDefaultPrettyPrinter();
// instantiate class I want to save
ExempleClass exempleClass = new ExempleClass();
// create empty file
File file = new File("D:/Desktop/exemple.json");
new File("D:/Desktop/").mkdirs();
file.createNewFile();
saveWriter.writeValue(file, exempleClass);
System.out.println("Saved exemple.json on the desktop of the D drive");
} catch (Exception e) {
System.out.println("Exception attempting to save exemple");
e.printStackTrace();
}
}
private static class ScriptB extends Script {
@JsonProperty
private int keep;
public ScriptB() {
keep = 50;
}
}
// ignore this class
private static class ScriptA extends Script {
private int dontKeep;
public ScriptA() {
dontKeep = 25;
}
}
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, property = "className")
private static abstract class Script {
}
private static class ExempleClass {
@JsonProperty
private List<Script> scripts;
public ExempleClass() {
scripts = new ArrayList<>();
scripts.add(new ScriptA());
scripts.add(new ScriptB());
}
}
}