简体   繁体   中英

Jackson - Don't use @JsonProperty with @JsonPOJOBuilder or @JsonCreator ctor

Preconditions:

  • Java/Spring Boot
  • PropertyNamingStrategy.UpperCamelCaseStrategy is set
  • DTO classes fields are camel case
  • Json fields are upper camel case
  • DTO/Json field names are aligned
  • Keep DTO classes immutable, avoiding the use of setters for fields

Requirement:

  • Deserialize without using @JsonProperty in DTO class (implicitly)

Tried to use nested builder class with @JsonPOJOBuilder or constructor, annotated with @JsonCreator , however:

  • @JsonPOJOBuilder annotated Builder class without @JsonPropery on setField() methods - setField() methods not being called by Jackson on deserialization
  • Constructor with @JsonCreator annotation - explicitly requires @JsonProperty on parameters

I have written a blog post with a solution for this. In summary:

  1. use Java 1.8
  2. compile with -parameters argument
  3. use and register jackson-module-parameter-names

The above will result in Jackson finding the names of the arguments of the constructor in the bytecode without requiring either @JsonCreator or @JsonProperty on the constructor.

Regardig the naming strategy you can easily set it at applications.properties and although I haven't tested it, should work with the non-annotated constructor.

When using @JsonCreator use camel case.

I used snake case in below example. @JsonCreator public ApiResponseBuilder(@JsonProperty("status_code")int statusCode, @JsonProperty("status_message")String statusMessage) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM