Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON fields unordered

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

like image 592
gotz Avatar asked Mar 07 '12 23:03

gotz


People also ask

Does order of fields matter in JSON?

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.

Is JSON unordered?

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.

Why is JSON unordered?

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.


1 Answers

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
like image 129
Victor Petit Avatar answered Oct 06 '22 23:10

Victor Petit