user3334871
user3334871

Reputation: 1361

Java Spring - Ignore Null values in nested object class on GET

So, I have a bit of strange behavior. In my Spring app, I have two object classes, with one class nested inside the other. I'm using Jackson to Serialize my Object classes into JSON. In my second object class (ObjectB), I have 4 fields. Based on some UI condition, I either set field 1 and 2, or 3 and 4, but never all of them at once. I've included the Jackson annotation to ignore null fields, and it works. In my DB, after I submit, I only see field 1 and 2 OR 3 and 4.

The issue comes when I get my data from the DB. To map the JSON into my Object class, I have to set the fields in my ObjectB class when parsing ObjectA. This leads me to see all 4 fields being returned, with half of their values showing as null. I print this info to my UI, so I want to make it more readable by not having the null values being returned. Is there anyway to do this? I'll post a code example of what I am trying to do.

ObjectA.class

@JsonAutoDetect(fieldVisibility = Visibility.ANY, isGetterVisibility = Visibility.NONE, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ObjectA {

   String field_A1;
   String field_A2;
   ObjectB field_A3;

   //Getters and Setters
}

ObjectB.class

@JsonAutoDetect(fieldVisibility = Visibility.ANY, isGetterVisibility = Visibility.NONE, getterVisibility = Visibility.NONE, setterVisibility = Visibility.NONE)
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class ObjectB {

   String field_B1;
   String field_B2;
   String field_B3;
   String field_B4;

   //Getters and Setters
}

Data in DB - Object1:{field_A1:"abc",field_A2:"def",field_A3:{field_B1:"ghi",field_B2:"jkl"}}

Mapping logic for Class ObjectA

ObjectA objA = new ObjectA();
...
ObjectB objB = new ObjectB();
if(jsonObj.get("field_B1") != null) {
    objB.setField_B1(jsonObj.get("field_B1"));
}

if(jsonObj.get("field_B2") != null) {
    objB.setField_B2(jsonObj.get("field_B2"));
}

if(jsonObj.get("field_B3") != null) {
    objB.setField_B3(jsonObj.get("field_B3"));
}

if(jsonObj.get("field_B4") != null) {
    objB.setField_B4(jsonObj.get("field_B4"));
}

objA.setField_3(objB);

Data returned to the UI - Object1:{field_A1:"abc",field_A2:"def",field_A3:{field_B1:"ghi",field_B2:"jkl",field_B3:null,field_B4:null}}

Upvotes: 2

Views: 2621

Answers (1)

LppEdd
LppEdd

Reputation: 21134

I'm still not sure which version of Spring you're using, but from 4+, if I remember correctly, you can define a custom Jackson ObjectMapper Bean.

@Bean
@Primary
public ObjectMapper customObjectMapper() {
   final ObjectMapper mapper = new ObjectMapper();
   ...
   mapper.setSerializationInclusion(Include.NON_NULL);
   return mapper;
}

Upvotes: 2

Related Questions