Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonNode comparison excluding fields

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.

like image 811
Mkl Rjv Avatar asked Nov 03 '18 12:11

Mkl Rjv


2 Answers

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);
like image 136
user7294900 Avatar answered Sep 28 '22 07:09

user7294900


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}
like image 30
ToYonos Avatar answered Sep 28 '22 08:09

ToYonos