Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON ORDER_MAP_ENTRIES_BY_KEYS not working consistently

Tags:

java

json

I am trying ORDER_MAP_ENTRIES_BY_KEYS, following what I read in this question:

[Jackson JsonNode to string with sorted keys

but it does not seem to work when printing JsonNode object.

For example, the following code:

ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);

HashMap<String,String> personHashMap = new HashMap<String,String>();
personHashMap.put("First", "Joe");
personHashMap.put("Last", "Bloe");
personHashMap.put("Age",  "32");
System.out.println("-- Printing personHashMap         gives:\n"+mapper.writeValueAsString(personHashMap));

String personJsonNode =
    "{\"Last\": \"Bloe\", \"First\": \"Joe\", \"Age\": \"32\"}";
JsonNode personJsonObj = mapper.readTree(personJsonNode);
System.out.println("-- Printing personJsonNode     gives:\n"+mapper.writeValueAsString(personJsonObj));

prints the following output:

-- Printing personHashMap gives:

{
  "Age" : "32",
  "First" : "Joe",
  "Last" : "Bloe"
}
-- Printing personJsonNode gives:

{
  "Last" : "Bloe",
  "First" : "Joe",
  "Age" : "32"
}

Notice how the person personHashMap WAS sorted by keys, but not the personJsonNode object.

What am I doing wrong? Thx.

like image 646
Alain Désilets Avatar asked Jan 15 '16 18:01

Alain Désilets


1 Answers

It's because ORDER_MAP_ENTRIES_BY_KEYS only applies to Maps, not JsonNodes (which is a weird design decision, but...). That's why the answer you reference converts the JsonNode tree into an Object before stringifying it. You need to do the same in your code.

like image 181
elhefe Avatar answered Oct 25 '22 15:10

elhefe