Search code examples
jacksonswagger-codegen

Jackson strips leading underscore


Our swagger specification defines a property _links.

places-result:
  type: object
  properties:
    _links:
      $ref: "#/components/schemas/links-underscore-type"

Using swagger-codegen, we see this name end up in the output class:

@JsonProperty("_links")
private LinksUnderscoreType _links = null;

@Schema(
    description = ""
)
@Valid
public LinksUnderscoreType getLinks() {
    return this._links;
}

However, Jackson adds a property with and without the leading underscore:

{
  "result": {
    "links": {
        "self": "http://localhost:8083/places?page=181",
        "previous": "http://localhost:8083/places?page=180",
        "first": "http://localhost:8083/places?page=0"
    },
    "_links": {
        "self": "http://localhost:8083/places?page=181",
        "previous": "http://localhost:8083/places?page=180",
        "first": "http://localhost:8083/places?page=0"
    }
}

As it is a Spring Boot application, we should be able to influence the naming strategy using this property:

spring.jackson.property-naming-strategy: LOWER_CASE

None of the accepted values seems to preserve the specified property name.

How can we preserve the leading underscore?


Solution

  • It turns out the non-underscore property came in because it was matched by the getter method. The solution is to not match the getter methods. This can be achieved in the Spring Boot config:

    spring:
      jackson:
        mapper:
          AUTO_DETECT_GETTERS: false
    

    Or in code:

    objectMapper.configure(MapperFeature.AUTO_DETECT_GETTERS, false);