Jackson JsonNode to string with sorted keys

后端 未结 1 1399
情书的邮戳
情书的邮戳 2021-01-01 11:22

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 opposi

相关标签:
1条回答
  • 2021-01-01 11:55

    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;
    }
    
    0 讨论(0)
提交回复
热议问题