1

The following response object results in the very same order in JSON format:

public SpecificResponse {

    private int id;
    private int processId;
}

{ "id": 1, "processId": 1 }

When this object inherits from ProcessResponse having an extra field List<Message> messages, this field suddenly comes as first in the JSON response:

{
    "messages": [{
        "code": "CODE1",
        "Message": "Bla..."
    }, {
        "code": "CODE2",
        "Message": "Ble..."
    }],
    "id": 1,
    "processId": 1
}

I want to have messages field (and others) as last. There is a way to push messages to the end of the JSON using:

@JsonPropertyOrder({ "id", "processId", "messages"})

This solution becomes hell in case there are a lot of instance fields inherited. Is there another way explicitly specifying that the inherited fields come last for selected objects?

Nikolas Charalambidis
  • 29,749
  • 7
  • 67
  • 124
  • 1
    ...but [JSON keys lack stable order](https://stackoverflow.com/a/38218582/1079354). Why do you require this? – Makoto Mar 30 '20 at 16:48
  • 4
    Order shouldn't matter in a JSON payload in general. Relying on order seems like a fragile solution. You could maybe write a custom serializer, but I'm not sure how you'd know what order things are supposed to go in. – Christopher Schneider Mar 30 '20 at 16:49
  • @ChristopherSchneider: ... purely for development and testing purposes. It's irrelevant for machine processing, but when we repeatedly call the endpoint, we'd like to have the most important information on the top and the inherited bloat on the bottom of the long response... why would the `@JsonPropertyOrder` annotation exist otherwise? – Nikolas Charalambidis Mar 30 '20 at 16:53
  • 1
    It's most likely there for pretty printing, as opposed to anything else. I *really* don't believe that any solution which explicitly mandates an order is going to be all that useful, and that your testing and development should incorporate actual JSON parsing as opposed to eyeball validation. – Makoto Mar 30 '20 at 16:56
  • @Nikolas the above comments are right. If you are indeed relying on the order of the json payload then something is wrong in your testing/development and you need to revisit that. – dondragon2 Mar 30 '20 at 17:28
  • @dondragon2: As I said, I would never go for such a solution that relies on the order (actually I have never say it, please read more carefully). All I want is to have the response pretty-printed and the important (not-inherited) fields first as long as we develop and look to the response with our own eyes for the sake of development. – Nikolas Charalambidis Mar 30 '20 at 17:36

0 Answers0