Generically Pulling Fields Out of Java Beans

You may run across a use case where you do not know exactly what data you are receiving and cannot make a POJO for Jackson to model. In this instance you may want to simply convert all non null properties. We are Jackson-lite in this instance. We can also provide a list of fields we know we do not want to convert:

  public Map<String, Object> getNonNullProperties(
      final Object objectToIntrospect, List<String> denyListFields) {
    final Map<String, Object> nonNullProperties = new TreeMap<>();
    try {
      final BeanInfo beanInfo = Introspector.getBeanInfo(objectToIntrospect.getClass());
      for (final PropertyDescriptor descriptor : beanInfo.getPropertyDescriptors()) {
        try {
          final Object propertyValue = descriptor.getReadMethod().invoke(objectToIntrospect);
          if (propertyValue != null && !denyListFields.contains(descriptor.getName())) {
            nonNullProperties.put(descriptor.getName(), propertyValue);
          }
        } catch (final IllegalArgumentException
            | IllegalAccessException
            | InvocationTargetException e) {
          // handle
        }
      }
    } catch (final IntrospectionException e) {
      // handle
    }
    return nonNullProperties;
  }

This is a good stopgap until a more formal ICD is formed or data collapses down into a known entity.

Initial inspiration from Stack Overflow.