Lombok字符串数组属性

huangapple 未分类评论45阅读模式
英文:

Lombok String Array Property

问题

以下是翻译好的内容:

有没有办法将 JSON 对象中的数组值用作 lombok 值。例如,请求体如下:

{
  "associatedCompanyIds": [
    332510120384
  ]
}

转化为:

@lombok.value
private static class Payload {
    private List<String> associatedCompanyIds;
}

我知道这样做行不通,但我正在尝试类似这样的操作,以便可以提取数组的第一个值。

英文:

Is there away to use an array value from a JSON object as a lombok value. For example the body

{
&quot;associatedCompanyIds&quot;: [                                                                                                                                                                                                                 
      332510120384                                                                                                                                                                                                                              
    ]
}

As

@lombok.value
private static class Payload{
    private List&lt;String&gt; associatedCompanyIds; 
}

I know this won't work, but I'm trying to do something similar to this so that I can extract that first value of the array.

答案1

得分: 0

这几乎可以直接使用。您唯一需要做的是告诉 Lombok 生成一个 @java.beans.ConstructorProperties 注解,以便 Jackson 知道要将哪个构造函数参数用于哪个 JSON 值。
只需在项目根文件夹中创建一个名为 lombok.config 的文件,并包含以下内容:

lombok.anyConstructor.addConstructorProperties = true
config.stopBubbling = true

缺点是 Jackson 会传递一个可变的 ArrayList。因此,如果您想要一个真正的不可变值类,您需要使用 lombok 的 @Builder@Singular

@Builder(setterPrefix = "with")
@JsonDeserialize(builder = Payload.PayloadBuilder.class)
@Value
public class Payload {
    @Singular
    private List<String> associatedCompanyIds;
}

采用这种方法甚至不需要 lombok.config,但至少需要 lombok 版本为 v1.18.12(因为涉及到 setterPrefix)。

英文:

This works almost out of the box. The only thing you have to do is to advise lombok to generate a @java.beans.ConstructorProperties annotation, so that Jackson knows which constructor parameter to use for which JSON value.
Simply create a lombok.config in your project root folder with this content:

lombok.anyConstructor.addConstructorProperties = true 
config.stopBubbling = true

The drawback is that Jackson will pass an ArrayList, which is mutable. So if you want a truely immutable value class, you have to use lombok's @Builder with @Singular:

@Builder(setterPrefix = &quot;with&quot;)
@JsonDeserialize(builder = Payload.PayloadBuilder.class)
@Value
public class Payload {
	@Singular
	private List&lt;String&gt; associatedCompanyIds;
}

You don't even need the lombok.config with this approach, but you need at least lombok v1.18.12 (because of the setterPrefix).

huangapple
  • 本文由 发表于 2020年4月8日 01:37:48
  • 转载请务必保留本文链接:https://java.coder-hub.com/61086036.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定