André Ribeiro
André Ribeiro

Reputation: 59

How to ignore JSON properties similar to @JsonIgnore in Deserialization

I have a JSON object similar below:

[
  {
     "objA": {
       "propA": "AAAA",
       "propB": "BBBB",
       "objB": {
         "objC": {
           "propC": "CCCC",
           "propD": "DDDD"
         }
       },
       "objD": [
         "asa"
       ],
       "propE": "AW",
       "propF": "533",
       "propG": "ABW",
       "propH": "ARU",
       "objE": {
         "objF": {
           "propI": "SASDS",
           "propJ": "54DEFF"
         }
       }
     }
   }
]

When I deserialize this JSON into a List, I would like to do for part of this object, for example: I would like to ignore objB, objC, objD, objE and objF. To do that I has been used the @JsonIgnore annotation. So I did something like that:

public class MyClass {

// objects and properties not ignorabled
private ClassA objA;
private String propE;
private String propF;
private String propG;;
private String propH;

// objects ignorabled in deserialization 
@JsonProperty("objB")
@JsonIgnore
private Object objB;

@JsonProperty("objD")
@JsonIgnore
private Object objD;

@JsonProperty("objE")
@JsonIgnore
private Object objE;

/** gets and setters here **/

Follow below the piece of code that deserialize my JSON

ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(url, new TypeReference<List<MyClass>>(){});

This code is working. this code is ignoring the objects from JSON, but I believe there are some another way to do that instead of use @JsonIgnore to each object or property in my entity.

Do you know how can I do that better?

Upvotes: 0

Views: 4095

Answers (1)

brighthammer
brighthammer

Reputation: 51

Do you want to avoid using @ notations ?

If not, have you tried using a filter like @JsonFilter("myFilter") in Jackson ? As described here: https://www.baeldung.com/jackson-ignore-properties-on-serialization

See also https://www.tutorialspoint.com/jackson_annotations/jackson_annotations_jsonfilter.htm

So you would have to write:

@JsonFilter("myFilter")
public class MyClass { ... }

in your class. Then do something like:

SimpleBeanPropertyFilter objBFilter = SimpleBeanPropertyFilter
  .serializeAllExcept("objB");
SimpleBeanPropertyFilter objDFilter = SimpleBeanPropertyFilter
  .serializeAllExcept("objD");
SimpleBeanPropertyFilter objEFilter = SimpleBeanPropertyFilter
  .serializeAllExcept("objE");

FilterProvider filters = new SimpleFilterProvider()
  .addFilter("objBFilter", theFilter)
  .addFilter("objDFilter", theFilter)
  .addFilter("objEFilter", theFilter);

Upvotes: 1

Related Questions