Search code examples
javajsonjacksonjackson-databind

Automatic discovery of getters without get prefix


Is it possible to have jackson automatically discover getters that are not named using the getFoo() naming scheme, but instead are just named foo()?

Example:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

class Test {
    private final String foo;

    public Test(String foo) {
        this.foo = foo;
    }

    public String foo() {
        return foo;
    }
}

class Scratch {
    public static void main(String[] args) throws JsonProcessingException {
        final ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.writeValueAsString(new Test("example")));
    }
}

Here, the foo() getter is not recognized by jackson. One solution in this case would be to annotate the getter with @JsonProperty. However, I'm looking for a way to do this without having to annotate each single getter manually.


Solution

  • Impossible; the only recognizable aspect here (because 'delve into the bytecode and check if it merely returns a field' is definitely not acceptable, as that's internal details that can change in minor updates, and thus, off limits) is 'any method that has no parameters, isn't static, and returns something else than void).. but other methods might do that too. For example, string's toLowerCase(), which certainly isn't a getter in any way or form.

    So, even without having any idea of what jackson's capabilities are, what you are asking for is literally completely impossible. It's some pre-established name pattern (such as getX), or an annotation, or an explicit list. No other options.