Immutable Lombok annotated class with Jackson

后端 未结 9 2264
再見小時候
再見小時候 2020-12-25 13:02

What is the preferred way to create class that is

  • Immutable
  • Can be serialized/deserialized with Jackson
  • Human-readable and with low level of
9条回答
  •  北荒
    北荒 (楼主)
    2020-12-25 13:47

    add ConstructorProperties:

    • Create a lombok.config file in an appropriate location with the line: lombok.anyConstructor.addConstructorProperties = true
    • Add lombok @Value annotation to your class to make it immutable

    Then serialization and deserialization by Jackson works as expected.

    This method:

    • meets the criteria
    • has less boilerplace than the previous top answer
    • works on v1.16.20 (January 9th, 2018) and later

    Edit: 2020-08-16

    • Note: Using @Builder with @Value causes this solution to fail. (Thanks to comment from @guilherme-blanco below.) However, if you also add e.g. @AllArgsConstructor it does still work as expected.

提交回复
热议问题