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.Feature
s 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
?
We can access a field, array or nested object using the get() method of JsonNode class. We can return a valid string representation using the asText() method and convert the value of the node to a Java int using the asInt() method of JsonNode class.
JsonNode is Jackson's tree model (object graph model) for JSON. Jackson can read JSON into a JsonNode instance, and write a JsonNode out to JSON. This Jackson JsonNode tutorial will explain how to deserialize JSON into a JsonNode and serialize a JsonNode to JSON.
JsonNode represents any valid Json structure whereas ObjectNode and ArrayNode are particular implementations for objects (aka maps) and arrays, respectively.
ObjectNode is a concrete implementation of JsonNode that maps a JSON object, and a JSON object is defined as following: An object is an unordered set of name/value pairs.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With