9

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.

Community
  • 1
  • 1
Alain Désilets
  • 509
  • 5
  • 11

1 Answers1

11

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.

elhefe
  • 3,404
  • 3
  • 31
  • 45