79311112

Date: 2024-12-27 07:01:01
Score: 0.5
Natty:
Report link

To count the number of non-null fields of an object, I converted the object to a map and counted the non-null values in the map.

import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;
import java.util.Objects;

new ObjectMapper().convertValue(theObject, Map.class).values().stream().filter(Objects::nonNull).count();

Please make sure you have JsonInclude.Include.ALWAYS on the Class or you can set it in the mapper. mapper.setDefaultPropertyInclusion(JsonInclude.Include.ALWAYS);

If you don't want to include any field, @JsonIgnore can be used on the field.

Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • User mentioned (1): @JsonIgnore
  • Low reputation (0.5):
Posted by: Shivendra Kadam