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.
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.
It's possible to override annotation processing as if the assessors without get
prefix will be considering as annotated as the getters.
mapper.setAnnotationIntrospector(new JacksonAnnotationIntrospector() {
@Override
public PropertyName findNameForSerialization(Annotated a) {
PropertyName result = super.findNameForSerialization(a);
if (result == null) {
final AnnotatedElement classMember = a.getAnnotated();
if (classMember instanceof Method) {
final Method method = (Method) classMember;
if (method.getParameterCount() == 0 && (method.getModifiers() & (Modifier.STATIC | Modifier.ABSTRACT)) == 0)
try {
final Field field = method.getDeclaringClass().getDeclaredField(method.getName());
if (field.getType().equals(method.getReturnType())
&& (field.getModifiers() & Modifier.STATIC) == 0
) {
result = new PropertyName(field.getName());
}
} catch (NoSuchFieldException e) {
// ignore
}
}
}
return result;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With