0

I am using objectmapper to convert the class into json. Following is the code:

JSONParser parser = new JSONParser();
ObjectMapper mapper = new ObjectMapper();
String obj = mapper.writeValueAsString(myClass);
JSONObject jsonObject = (JSONObject)parser.perse(obj);

now line number 4 where I get the jsobObject reshuffles the order of class member. See the attached image, before it converting to jsonobject "authorisation" was first element then signatries. enter image description here But at line 4 it becomes 2nd ..... why ? I want order to be preserved, that is the requirement of my project. Please help !

user2746466
  • 361
  • 5
  • 23
  • 2
    Why does it matter what order they are in? The JSON spec states that an object is an unordered set of name/value pairs. See this question: [Does the sequence of the values matter in a JSON object?](https://stackoverflow.com/questions/16870416/does-the-sequence-of-the-values-matter-in-a-json-object) – Dave S Nov 12 '21 at 14:59
  • For our project requirement it needs to be in order, as we are converting it to JWT token. This JWT token process of our project requires the same order. – user2746466 Nov 12 '21 at 15:01
  • `@JsonPropertyOrder` only applies to *serialization(only)*! objects/json have no "property order"! ;) – xerx593 Nov 12 '21 at 15:01
  • Can I add my json class object member manually ? Creating the object of 'JSONObject' and adding the members in that manually ? Will that preserver the order while addition ? – user2746466 Nov 12 '21 at 15:09
  • Someone created a bug report for JWT regarding order of json object: [Order of JSON key, value pairs](https://github.com/auth0/node-jsonwebtoken/issues/148). It was closed because they concluded that even though the token looks different when the order changes, when the receiver decodes it the result will be the same regardless of order. Does that help you? – Dave S Nov 12 '21 at 16:20
  • No Dave, I tried it in my project, it is not working. It requires order. – user2746466 Nov 12 '21 at 16:25
  • Anybody has idea around Google json ? – user2746466 Nov 12 '21 at 16:35
  • Is it possible to change your JWT token process so that the same order is not required? It seems to me that order should not be a requirement for the JWT process. So if your project's process won't work unless the values are in a certain order, and the JSON spec says that order does not matter, couldn't that be considered a bug in that JWT process? – Dave S Nov 13 '21 at 04:48

1 Answers1

0

You can configure the ordering this way :

@JsonPropertyOrder({ "authorisation", "signatoryDetails", "requestedLimits" })
public class MyClass { ... }
Tom
  • 4,972
  • 3
  • 10
  • 28