Lombok + Jackson不可变类

16

将我的项目更新到Spring Boot 1.5.10后,Lombok与Jackson不再正确工作。我指的是创建不可变DTO,当我的对象中的字段名称与json请求中的字段不同时:

@Value
@Builder
public class MyImmutableDto implements Serializable {

    @JsonProperty("other-field-1-name")
    private final BigDecimal myField1;

    @JsonProperty("other-field-2-name")
    private final String myField2;

    and a lot of fields there...
}
所以,在将Spring Boot更新为1.5.10之后,这段代码不起作用了,我需要像这样配置lombok:
lombok.anyConstructor.addConstructorProperties = true

有没有其他方法可以使用jackson + lombok创建这种对象而不需要使用lombok的修复方法呢? 除了这个修复方法,我可以使用以下代码:@JsonPOJOBuilder@JsonDeserialize(builder = MyDto.MyDtoBuilder.class)

@Value
@Builder
@JsonDeserialize(builder = MyDto.MyDtoBuilder.class)
public class MyDto implements Serializable {

    // @JsonProperty("other-field-1-name")    // not working
    private final BigDecimal myField1;

    private final String myField2;
    private final String myField3;
    and a lot of fields there...

    @JsonPOJOBuilder(withPrefix = "")
    public static final class MyDtoBuilder {
    }
}

但是在 @JsonProperty("other-field-1-name") 上不起作用。 当然,可以通过简单的 @JsonCreator 来完成,但也许有一些方法可以使用 lombok 以及一些构造函数/ jackson 注释来实现?


我没有成功地使用第一种方法解决原始问题,所以我转而使用第二种方法,并发现(当然)字段上的Jackson注释不会传递到构建器方法中,因此我对接下来会发生什么很感兴趣。 - simon
@simon 发布了一个对我有用的答案。只想确认您在遇到此问题时使用的版本。 - shinjw
你可以在不可变性和Jackson中使用Lombok:答案 - Oleksandr Yefymov
你可以同时使用Lombok Builder和Jackson: https://dev59.com/kek6XIcBkEYKwwoYAfO1#48801237 - ganesan dharmalingam
2个回答

2

所以这不是完全相同的情况,但对于我的问题有效。我需要在构建器上使用@JsonDeserialize注释,将其明确放置在构建器上可以解决问题(代价是样板代码)。至少我不需要输入构建器的其余部分。

@Value
@Builder
@JsonDeserialize(builder = ProductPrice.ProductPriceBuilder.class)
public class ProductPrice {

    @JsonSerialize(using = MoneySerializer.class)
    @JsonDeserialize(using = MoneyDeserializer.class)
    Money price;

    Duration rentalLength;

    Period recurrence;

    @JsonPOJOBuilder(withPrefix = "")
    public static class ProductPriceBuilder{
        @JsonDeserialize(using = MoneyDeserializer.class)
        public ProductPrice.ProductPriceBuilder price(Money price) {
            this.price = price;
            return this;
        }  
    }
}

0

考虑到这个问题是在2017年1月之后提出的,我假设您可能已经升级了Lombok版本1.16.20并使用Spring Boot。同时仍在使用JDK 8。

您可以更新Spring Boot版本,但可能希望将Lombok版本保持在1.16.18。这将让您通过构建器解决方案实现额外的自定义和反序列化。也就是说,只要您没有使用任何新的lombok注释。

在1.16.20中特别投入了大量精力来解决JDK 9中的破坏性变化,这可能会在JDK 8上引起未来的问题。

1.16.20 @Data object no longer constructable for jackson? <其他发现类似问题的人。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接