Home > Enterprise >  Spring boot - Customize order of properties in response
Spring boot - Customize order of properties in response

Time:07-16

I have a base model class with createdAt and updatedAt properties, and a user model extending that class, when spring returns the json, it puts the createdAt / updatedAt properties first, which isn't breaking anything, just super weird to look at, so I end up with something like this:

{
    "createdAt": "2022-07-14T06:31:04.933027-04:00",
    "updatedAt": "2022-07-14T06:31:04.933027-04:00",
    "id": 1,
    "email": "[email protected]",
    "firstName": "Foo",
    "lastName": "Bar"
}

Ideally, I'd like it to look like this if possible / be able to customize the order:

{
    "id": 1,
    "email": "[email protected]",
    "firstName": "Foo",
    "lastName": "Bar",
    "createdAt": "2022-07-14T06:31:04.933027-04:00",
    "updatedAt": "2022-07-14T06:31:04.933027-04:00"
}

CodePudding user response:

I was facing the exactly same issue just as you do - I wanted the createdDate/updateDate from base class and only want them shown at the bottom.

annotation JsonPropertyOrder is the answer.

option 1) specify each property name in desired order in this annotation(put on class level), i.e.:

@JsonPropertyOrder(value = {"id", "email", "firstName", "lastName", "createdAt", "updatedAt"})
public class SubClass {
    
}

however, it's not good practice to hardcode property names as plain text, which lead to unexpected order in case you renamed an property but not updated the hardcoded name to be the same.

option 2) as this answer says https://stackoverflow.com/a/70165014/6228210, use the annotation JsonProperty to customize the order of each property. I verified it works very well.

see sample, copied from that SO:

class animal {
    @JsonProperty(index=2)
    int p1;
    @JsonProperty(index=3)
    int p2;
}

class cat extends animal{
    @JsonProperty(index=1)
    int p3;
}

I personally believe this is better option.

to improve it a bit, I would suggest specifying the index this way, like 5, 10, 15, 20... for sub class and a big number 99 and 100 for base class properties, which makes it easy for you to insert new properties in the future and won't mess up the orders.

CodePudding user response:

Normally the order should be the same as the model. If you want to change the order, do it in the model.

  • Related