I am writing some RESTful services using spring MVC. I am using jsckson mapper to do the It conversions. It all works fine except that the json it produces has fields completely unordered.
for e.g. If my entity object looks like this:
public class EntityObj
{
private String x;
private String y;
private String z;
}
If I now have a list of EntityObjs, and I return this back from the controller, the json has the order mixed up for the fields e.g.: [{y:"ABC", z:"XYZ", x:"DEF"},{y:"ABC", z:"XYZ", x:"DEF"}]
Looked around for a solution but not finding any. Anyone else faced this issue?
Thanks for the help
what is the use for order the fields? From json.org "An object is an unordered set of name/value pairs." You should write your JSON processor so that order doesn't matter.
JSON objects are unordered sets of name and value pairs. Objects are written inside of curly braces, like these { }. Everything inside the curly braces is part of the object.
The JSON Data Interchange Standard definition at json.org specifies that “An object is an unordered [emphasis mine] set of name/value pairs”, whereas an array is an “ordered collection of values”. In other words, by definition the order of the key/value pairs within JSON objects simply does not, and should not, matter.
If alphabetical order suit you and you are using Spring Boot, you can add this in your application.properties
:
spring.jackson.mapper.sort-properties-alphabetically=true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With