3

Jackson doesn't handle my boolean fields with a has getter method. For example animal.hasLegs(), for the legs field returns a JSON object without the legs field. It does work with the is getter method (person.isAwesome() for the boolean field awesome).

How can I make Jackson use the has method naming convention for boolean fields?

Jelle den Burger
  • 1,428
  • 17
  • 31
  • 2
    Note: there is no "has" naming convention. The "is" convention is defined in the JavaBeans spec (although even that is an exception), so making getters for booleans with "has", "can", "should" or any other similar prefix is bound to break many applications. Nothing prevents you from creating additional getters though. – Kayaman Mar 03 '17 at 13:08
  • @Kayaman although it might not be official, it is pretty common to use the `has` naming. For example, check out this SO question: http://stackoverflow.com/questions/3874350/naming-conventions-for-java-methods-that-return-booleanno-question-mark – Jelle den Burger Mar 03 '17 at 14:12
  • It's still not in the spec. If it were in the spec, it would work automatically. – Kayaman Mar 03 '17 at 14:14
  • Having you tried annotating your getters and setters with `@JsonProperty(value="Name of the field")` ? – Coder Mar 03 '17 at 22:27
  • Ran into issues with Jackson and `is` naming. Moral of story... recommend that despite aesthetics , use `get` everywhere for properties. Avoid `is`, `has`, etc... coders later will not care that much vs. the hell you'll need to deal with for serialization. If you really want an extra verb, maybe `getIsSomething()`. That way your property is at least named `isSomething`. – Ray Oct 22 '18 at 12:28
  • Thank you @Kayaman. Finally I found the manual by the keyword "JavaBeans spec" about isXXXXX() naming conventions – Ninja Dec 22 '21 at 03:22

1 Answers1

5
  1. Annotate all needed hasXXX() methods with @JsonGetter. Otherwise Jackson doesn't use this property at all, because it doesn't start with get:

    @JsonGetter
    public boolean hasAwesome() { ... }
    
  2. Set custom PropertyNamingStrategy, which renames mapping from method name to JSON field. By default it will generate JSON field named hasXXX.

    ObjectMapper mapper = ...
    mapper.setPropertyNamingStrategy(new PropertyNamingStrategy() {
        @Override
        public String nameForGetterMethod(MapperConfig<?> config, AnnotatedMethod method, String defaultName) {
            String prefix = "has";
            if (defaultName.startsWith(prefix)) {
                String withoutHas = defaultName.replace(prefix, "");
                char firstLower = Character.toLowerCase(withoutHas.charAt(0));
                return firstLower + withoutHas.substring(1);
            }
            return super.nameForGetterMethod(config, method, defaultName);
        }
    });
    
Evgeny Veretennikov
  • 3,889
  • 2
  • 16
  • 36