I'm trying to deserialise a JSON string using ObjectMapper
(Jackson) and exclude a field while performing the deserialisation.
My code is as follows:
String aContent = new String(Files.readAllBytes(Paths.get(aFile)));
String bContent = new String(Files.readAllBytes(Paths.get(bFile)));
ObjectMapper mapper = new ObjectMapper();
FilterProvider filterProvider = new SimpleFilterProvider()
.addFilter("_idFilter", SimpleBeanPropertyFilter.serializeAllExcept("_id"));
mapper.setFilterProvider(filterProvider);
JsonNode tree1 = mapper.readTree(aContent);
JsonNode tree2 = mapper.readTree(bContent);
String x = mapper.writeValueAsString(tree1);
return tree1.equals(tree2);
Both x and tree1 and tree2 contains the value _id in the JSON String but it isn't removed.
You are following Ignore Fields Using Filters except the first step
First, we need to define the filter on the java object:
@JsonFilter("myFilter") public class MyDtoWithFilter { ... }
So currently you supposed to add
@JsonFilter("_idFilter")
public class JsonNode {
It's not possible so you need to create a class that extends JsonNode
and use it instead
@JsonFilter("_idFilter")
public class MyJsonNode extends JsonNode {
If you don't want to implement all abstract method define as abstract
@JsonFilter("_idFilter")
public abstract class MyJsonNode extends JsonNode {
}
And in your code:
MyJsonNode tree1 = (MyJsonNode) mapper.readTree(aContent);
MyJsonNode tree2 = (MyJsonNode) mapper.readTree(bContent);
FilterProvider
are meant to be used with custom Object like here
If you want to stick with JsonNode
, use this method :
String aContent = new String("{\"a\":1,\"b\":2,\"_id\":\"id\"}");
ObjectMapper mapper = new ObjectMapper();
JsonNode tree1 = mapper.readTree(aContent);
ObjectNode object = (ObjectNode) tree1;
object.remove(Arrays.asList("_id"));
System.out.println(mapper.writeValueAsString(object));
Will print :
{"a":1,"b":2}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With