简体   繁体   中英

Jackson's @JsonPropertyOrder doesn't work with @JsonUnwrapped

I have an object that contains another object attribute like this:

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:

{
  "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. 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.

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


But you may consider a workaround : as you seem to be using Lombok, you could annotate b with @Delegate and @JsonIgnore :

@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.

And the @Delegate annotation will tell Lombok to generate delegate methods that forward the call to the B methods. With that, the A class will have getters and setters that are delegated to the getters and setters of the fB1 and fB2 fields.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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