1

I have a class with a private constructor that I cannot modify containing many final fields that I wish to serialize with Jackson. Is there any way to force Jackson to serialize all the final fields?

I've tried using a custom filter provider like so: new ObjectMapper().setFilterProvider(new SimpleFilterProvider().addFilter("serialize-final", SimpleBeanPropertyFilter.serializeAll())) but Jackson seems to filter out the final fields before/after it applies my filter.

The use case is my program depends on a library that uses feature flags to indicate which features are enabled. The distributor of the library has compiled the feature flags into final fields on a singleton object that I am able to access at runtime. I wish to add the ability to dump the feature flags when requested to allow for easier debugging and simply serializing them as JSON seems like the easiest solution.

nulldev
  • 555
  • 6
  • 16

1 Answers1

0

I assume the singleton does not have getters for the final fields (else it works out of the box). You could use the field visibility checker as suggested in this answer:

    public class SerializeFinalFields {

        @Test
        public void doTest() throws JsonProcessingException {
            final TestClass t = new TestClass("flag");
            final ObjectMapper om = new ObjectMapper();
            // Older jackson versions:
            // om.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
            // om.setVisibility(
            //      om.getSerializationConfig().getDefaultVisibilityChecker()
            //              .withFieldVisibility(JsonAutoDetect.Visibility.ANY));
            // newer jackson versions:
            om.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);

            final String json = om.writeValueAsString(t);
            System.out.println(json);
        }

    }

    class TestClass {

        private final String myField;

        /* package */ TestClass(final String myField) {
            this.myField = myField;
        }
    }
sfiss
  • 2,119
  • 13
  • 19