Do not include property in POJO if it is null or doesn't exist in incoming JSON

Viewed 43

Hi I have the following object mapper:

public <T> T convertJSONtoPOJO(String inputJSON,
                               Class<T> valueType) throws Exception {
    try {
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
        return objectMapper.readValue(inputJSON, valueType);
    } catch (Exception exception) { 
        //my exception which doesnt matter now
    }
}

And incoming JSON:

{
    "propertyA": "1",
    "propertyB": null, 
}

And POJO:

@FieldDefaults(level = AccessLevel.PRIVATE)
@Data
public class MyClazz {
    String propertyA;
    String propertyB;
    String propertyC;
}

By default @JsonProperty required is set to false on all of them.

Now while deserializing I want to obtain POJO which does NOT include: a) non-required variables if they do NOT occur in JSON b) variables which have null value.

Currently my code does NOT fail, it simply gives me the following POJO:

propertyA = 1
propertyB = null
propertyC = null

But I want to obtain POJO with only:

propertyA = 1
2 Answers

If any of your fields are not required, you have to check them whether they are null or else, while using them. Because your class is represented by all the fields you define for it, and there is no way to ignore those fields with null values.

It's possible while serializing and converting to json, but not in deserializing.

One solution is create your own anotation @RequiredOnLoad

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface RequiredOnLoad { 
}

And your own load json, some like this:

//new function with check required fields
public <T> T myConvertJSONtoPOJO(String inputJSON,
                               Class<T> valueType) throws Exception {
   T pojo  = convertJSONtoPOJO(inputJSON,valueType);

   Field[] allFields = Person.class.getDeclaredFields();

   for (Field field : allFields)
   {
       if(field.isAnnotationPresent(RequiredOnLoad.class))
       {
          field.setAccessible(true);//to access private fields
          Object value = field.get(pojo);
          if (value == null ) 
          {
            throw new Exception("Field is required on load!");
          }
       } 
   }

   return pojo;
}
//old function without check
public <T> T convertJSONtoPOJO(String inputJSON,
{
...

Of course, in your POJO you need put the annotation when you field is required in load time

Related