Jackson JsonNode用排序键来串 [英] Jackson JsonNode to string with sorted keys

查看:126
本文介绍了Jackson JsonNode用排序键来串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Jackson 2.2.3 ,需要将JsonNode树转换为带有排序字段键的字符串。我完全不清楚如何做到这一点,特别是因为相反的事情很简单 - JsonNode jn = ObjectMapper.readTree(String s)

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).

看来正确的方法是 void writeTree(JsonGenerator jgen,JsonNode rootNode) 。但是,我认为无法从 String 。 0 / COM / fasterxml /杰克逊/型芯/ JsonGenerator.html?是-外部=真> JsonGenerator 。我认为 SerializationFeature .ORDER_MAP_ENTRIES_BY_KEYS 仍然适用,因为 JsonGenerator.Feature 没有该选项。有没有更简单的方法 - 或者如果没有,如何从 JsonGenerator 中检索序列化字符串?

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?

推荐答案

这是最简单的方法,由杰克逊的一位作者提供。目前无法直接从 JsonNode 到带有排序键的 String

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;
}

这篇关于Jackson JsonNode用排序键来串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆