Java Jackson JsonNode 使用排序键进行字符串处理

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18952571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 12:51:52  来源:igfitidea点击:

Hymanson JsonNode to string with sorted keys

javasortingHymanson

提问by elhefe

I'm using Hymanson 2.2.3and 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).

我正在使用Hymanson 2.2.3并且需要将 JsonNode 树转换为带有排序字段键的字符串。我完全不清楚如何做到这一点,特别是因为相反的事情非常简单 - 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 Stringfrom the JsonGenerator. I presume that SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYSwill 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?

看来正确的方法是void writeTree(JsonGenerator jgen,JsonNode rootNode)。但是,我认为没有办法StringJsonGenerator. 我认为这SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS仍然适用,因为JsonGenerator.Features 没有那个选项。有没有更简单的方法来做到这一点 - 或者如果没有,我如何从JsonGenerator?

采纳答案by elhefe

This is the easiest way to do it, as provided by one of Hymanson's authors. There's currently no way to go straight from JsonNodeto Stringwith sorted keys.

正如Hyman逊的一位作者所提供的那样,这是最简单的方法。目前没有办法使用排序的键直接从JsonNodeString

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