gpt4 book ai didi

java - Jackson 的 @JsonPropertyOrder 不适用于 @JsonUnwrapped

转载 作者:行者123 更新时间:2023-12-02 09:29:47 28 4
gpt4 key购买 nike

我有一个对象,其中包含另一个对象属性,如下所示:

import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonUnwrapped;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;

@JsonPropertyOrder({"fA1","b","fA2"})
@Data
public class A {
private String fA1;
private String fA2;

@JsonUnwrapped
private B b = new B();

@Data
class B {
private String fB1;
private String fB2;
}

public static void main(String[] args) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
A a = new A ();
System.out.println(objectMapper.writeValueAsString(a));
}

}

我想要的是生成尊重这个顺序的json:

{
"fA1":"",
"fB1":"",
"fA2":"",
"fB2":""
}

有什么办法可以做到这一点吗?

最佳答案

根据this issue在 GitHub 上的 jackson-databind 存储库中,@JsonPropertyOrder注释不适用于 @JsonUnwrapped注解。请参阅下面的引用:

True, unwrapped properties are not included in ordering, since they are not really known by enclosing serializer as regular properties. And specifically, as things are, will be output as a block of properties per contained, so even if known they can not be reordered separately.

Perhaps something could be done with Jackson 3.x once we get there.

<小时/>

但是您可以考虑一个解决方法:由于您似乎正在使用 Lombok,因此您可以使用 @Delegate 注释 b@JsonIgnore :

@Data
@JsonPropertyOrder({"fa1", "fb1", "fa2", "fb2"})
public class A {

private String fA1;
private String fA2;

@Delegate
@JsonIgnore
private B b = new B();
}

@JsonIgnore注释将确保 b 属性不会被 Jackson 序列化。

还有@Delegate注解将告诉 Lombok 生成委托(delegate)方法,将调用转发给 B 方法。这样,A 类将具有被委托(delegate)给 fB1fB2 字段的 getter 和 setter 的 getter 和 setter。

关于java - Jackson 的 @JsonPropertyOrder 不适用于 @JsonUnwrapped,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58081733/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com