33

I'm using Jackson 2.2.3 and need to convert a JsonNode tree into a string with sorted field keys. It's completely unclear to me how to do this, especially since the opposite is so simple - JsonNode jn = ObjectMapper.readTree(String s).

It appears the correct method is void writeTree(JsonGenerator jgen,JsonNode rootNode). However, I see no way to then get the serialized String from the JsonGenerator. I presume that SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS will still apply, since the JsonGenerator.Features don't have that option. Is there a simpler way to do this - or if not, how do I retrieve the serialized string from the JsonGenerator?

elhefe
  • 3,404
  • 3
  • 31
  • 45

1 Answers1

56

This is the easiest way to do it, as provided by one of Jackson's authors. There's currently no way to go straight from JsonNode to String with sorted keys.

private static final ObjectMapper SORTED_MAPPER = new ObjectMapper();
static {
    SORTED_MAPPER.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
}

private String convertNode(final JsonNode node) throws JsonProcessingException {
    final Object obj = SORTED_MAPPER.treeToValue(node, Object.class);
    final String json = SORTED_MAPPER.writeValueAsString(obj);
    return json;
}
elhefe
  • 3,404
  • 3
  • 31
  • 45
  • Is there a way to sort arrays inside JSON too? This solution do not works if you have json array: `{id:1, collection:[z, y]}` after seiralization if bacame `{collection:[z, y], id:1}` so items in *collection* did not ordered at all! :( – Cherry Jun 23 '14 at 05:57
  • 4
    @Cherry Just sort the array normally prior to serialization. The reason Jackson needs the ability to sort maps is because maps have no inherent ordering. Arrays do, and so the application can order the arrays as desired before serializing to JSON. This is not possible (in general) for maps. – elhefe Jun 23 '14 at 16:16