Immutable Lombok annotated class with Jackson

后端 未结 9 2136
再見小時候
再見小時候 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:55

    Try the following set of annotations for your pojo:

    @Value
    @NoArgsConstructor(force = true, access = AccessLevel.PRIVATE)
    @AllArgsConstructor
    
    0 讨论(0)
  • 2020-12-25 13:59

    You can use Lombok's @Builder annotation to generate a builder for your immutable POJO class. But making the Lombok-generated builder usable by Jackson's deserialization is somewhat tricky.

    • You need to annotate your POJO class with @JsonDeserialize(builder = ...) to tell Jackson which is the builder class to use.
    • You need to annotate the builder class with @JsonPOJOBuilder(withPrefix = "") to tell Jackson that its setter-methods do not start with with.

    Example:

    An immutable POJO class:

    @Data
    @Builder(builderClassName = "PointBuilder")
    @JsonDeserialize(builder = Point.PointBuilder.class)
    public class Point {
    
        private final int x;
    
        private final int y;
    
        @JsonPOJOBuilder(withPrefix = "")
        public static class PointBuilder {
            // Lombok will add constructor, setters, build method
        }
    }
    

    Here is a JUnit test to verify the serialization/deserialization:

    public class PointTest extends Assert {
    
        private ObjectMapper objectMapper = new ObjectMapper();
    
        @Test
        public void testSerialize() throws IOException {
            Point point = new Point(10, 20);
            String json = objectMapper.writeValueAsString(point);
            assertEquals("{\"x\":10,\"y\":20}", json);
        }
    
        @Test
        public void testDeserialize() throws IOException {
            String json = "{\"x\":10,\"y\":20}";
            Point point = objectMapper.readValue(json, Point.class);
            assertEquals(new Point(10, 20), point);
        }
    }
    
    0 讨论(0)
  • 2020-12-25 14:01

    The simplest way to configure immutable class for Jackson is to use lombok annotation: @Value and @Jacksonized:

        @Jacksonized
        @Builder
        @Value
        class Foo {
    
            
        }
    
    0 讨论(0)
提交回复
热议问题