Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson JsonNode to string with sorted keys

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?

like image 307
elhefe Avatar asked Sep 23 '13 05:09

elhefe


People also ask

How do you find the value of JsonNode?

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.

What is JsonNode Jackson?

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.

What is the difference between ObjectNode and JsonNode?

JsonNode represents any valid Json structure whereas ObjectNode and ArrayNode are particular implementations for objects (aka maps) and arrays, respectively.

What is difference between JsonNode and JSON object?

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.


1 Answers

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; } 
like image 177
elhefe Avatar answered Sep 20 '22 09:09

elhefe