简体   繁体   English

杰克逊的@JsonPropertyOrder 不适用于@JsonUnwrapped

[英]Jackson's @JsonPropertyOrder doesn't work with @JsonUnwrapped

I have an object that contains another object attribute like this:我有一个 object 包含另一个 object 属性,如下所示:

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

}

what i want is generate json that respect this order:我想要的是生成尊重这个顺序的 json:

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

Is there any way to do this?有没有办法做到这一点?

According to this issue in the jackson-databind repository on GitHub, the @JsonPropertyOrder annotation doesn't work with @JsonUnwrapped annotation.根据 GitHub 上 jackson-databind 存储库中的这个问题@JsonPropertyOrder注释不适用于@JsonUnwrapped注释。 See the quote below:请参阅下面的报价:

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.具体而言,将 output 作为每个包含的属性块,因此即使已知它们也不能单独重新排序。

Perhaps something could be done with Jackson 3.x once we get there.一旦我们到达那里,也许可以用 Jackson 3.x 做一些事情。


But you may consider a workaround : as you seem to be using Lombok, you could annotate b with @Delegate and @JsonIgnore :但是您可能会考虑一种解决方法:因为您似乎正在使用 Lombok,您可以使用@Delegate@JsonIgnore注释b

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

    private String fA1;
    private String fA2;

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

The @JsonIgnore annotation will ensure that the b property is not serialized by Jackson. @JsonIgnore注解将确保b属性不被 Jackson 序列化。

And the @Delegate annotation will tell Lombok to generate delegate methods that forward the call to the B methods. @Delegate注释将告诉 Lombok 生成将调用转发给B方法的委托方法。 With that, the A class will have getters and setters that are delegated to the getters and setters of the fB1 and fB2 fields.这样, A class 将具有委托给fB1fB2字段的 getter 和 setter 的 getter 和 setter。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM