永恒的龙目岛与杰克逊注释的类 [英] Immutable Lombok annotated class with Jackson

查看:103
本文介绍了永恒的龙目岛与杰克逊注释的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建类的首选方法是什么




  • 不可变

  • 可以序列化/用杰克逊反序列化

  • 人类可读且模板水平较低



最好是,我会喜欢这样的东西:

  @Data(onConstructor = @__(@ JsonCreator))

然后将所有字段设为 private final 。但是,这甚至没有编译(我不知道为什么)。使用

  @AllArgsConstructor(onConstructor = @__(@ JsonCreator))

将编译但仅产生

  InvalidDefinitionException:未找到序列化程序for class 


解决方案

你可以使用龙目岛的



这是一个用于验证序列化/反序列化的JUnit测试:

  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);
}
}


What is the preferred way to create class that is

  • Immutable
  • Can be serialized/deserialized with Jackson
  • Human-readable and with low level of boilerplate

Preferably, I would have liked something like this to work:

@Data(onConstructor = @__(@JsonCreator))

and then have all fields to be private final. However, this does not even compile (and I'm not sure why). Using

@AllArgsConstructor(onConstructor = @__(@JsonCreator))

will compile but only yields

InvalidDefinitionException: No serializer found for class

解决方案

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.

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);
    }
}

这篇关于永恒的龙目岛与杰克逊注释的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆