'Jackson @JsonPropertyOrder is ignored

I'm currently developing RESTful app with Spark framework and I use Jackson for serialization. And I encountered such issue: @JsonPropertyOrder is ignored.

Here's my POJO:

@Data
@JsonPropertyOrder({"id", "company", "title", "infos", "startDate", "endDate"})
public class Info {
    @JsonProperty("id")
    long id;

    @JsonProperty("company")
    Company company;

    @JsonProperty("title")
    String title;

    @JsonProperty("infos")
    List<Prize> infos;

    @JsonProperty("startDate")
    Date startDate;

    @JsonProperty("endDate")
    Date endDate;

    public Info() {}
}

I generate JSON with this method:

public static String generateJSONResponse(Object response) {
    if (responseObjectMapper == null) {
        responseObjectMapper = new ObjectMapper(new JsonFactory());
        responseObjectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    }

    try {
        return responseObjectMapper.writeValueAsString(response);
    } catch (IOException ioe) {
        // Must not occur
    }

    // Something really unexpected happened, so we return unknown response;
    return ErrorMessages.ERROR_RESPONSE_UNKNOWN;
}

And in the end I receive this:

{
  "status": 0,
  "result": {
    "infoList": [
      {
        "infos": [...],
        "id": 2,
        "title": "...",
        "company": {...},
        "startDate": 1445238000000,
        "endDate": 1445792400000
      },
      ...
    ]
  }
}

What am I doing wrong? Or something is wrong with Jackson? Can anybody help me with that?

Also, I tried this using Jackson version 2.6.3 and 2.3.5. Both works the same way.



Solution 1:[1]

check if you are importing the correct package of "JsonPropertyOrder":

this work for me: import com.fasterxml.jackson.annotation.JsonPropertyOrder;

Solution 2:[2]

The annotation JavaDoc also echoes the "unordered" collection: https://www.javadoc.io/doc/com.fasterxml.jackson.core/jackson-annotations/latest/com/fasterxml/jackson/annotation/JsonPropertyOrder.html

This annotation may or may not have effect on deserialization: for basic JSON handling there is no effect, but for other supported data types (or structural conventions) there may be.

That probably explains why it is not working.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Hoiama Rodrigues
Solution 2 Koray Tugay