Reputation: 750
Jackson is great for translating between POJO and json strings. But it's a pain to use it for manipulating a json string. I find myself doing stuff like:
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(ReadFile("testObj.json"));
((ObjectNode)node).put("testField", "newTestValue");
TestObject obj = mapper.readValue(mapper.writeValueAsString(node), TestObject.class);
And this is the simple example. It gets more complicated if you want to add a new object or an array of things. Is there a better way to do this?
Upvotes: 1
Views: 5080
Reputation: 279880
I don't see what's so difficult. If you are certain your root JSON is a JSON object, simply cast the value returned by ObjectMapper#readTree(..)
to an ObjectNode
and manipulate it.
String json = "{\"sample\": \"some value\", \"nested\": {\"prop\": 123, \"nestedArray\":[1,2, \"string value\"], \"array\":[null, 42]}}";
ObjectNode node = (ObjectNode) new ObjectMapper().readTree(json);
System.out.println(node);
ArrayNode arrayNode = node.putArray("new array");
arrayNode.add(true).add(1).add("new value"); // chain add calls
arrayNode.addObject().put("nestedInArray", "nested object value"); // add an object and add to it
System.out.println(node);
prints
{"sample":"some value","nested":{"prop":123,"nestedArray":[1,2,"string value"],"array":[null,42]}}
{"sample":"some value","nested":{"prop":123,"nestedArray":[1,2,"string value"],"array":[null,42]},"new array":[true,1,"new value",{"nestedInArray":"nested object value"}]}
Note that you can also add your custom objects too. They will typically be wrapped in POJONode
objects.
Upvotes: 3