英文:
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
{
"associatedCompanyIds": [
332510120384
]
}
As
@lombok.value
private static class Payload{
private List<String> 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 = "with")
@JsonDeserialize(builder = Payload.PayloadBuilder.class)
@Value
public class Payload {
@Singular
private List<String> 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
).
专注分享java语言的经验与见解,让所有开发者获益!
评论