Created
November 15, 2017 19:43
-
-
Save marcin-chwedczuk/2eaa34504a6b8365f74dbb43e61bb5b3 to your computer and use it in GitHub Desktop.
Modify JSON using FastXML Jackson without explicit deserialization
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static void main(String[] args) throws IOException { | |
ObjectMapper mapper = new ObjectMapper(); | |
mapper.enable(SerializationFeature.INDENT_OUTPUT); | |
ObjectNode rootNode = (ObjectNode) | |
mapper.readTree(Main.class.getResource("toModify.json")); | |
ArrayNode listOfObjectsToModify = | |
(ArrayNode) rootNode.get("listOfObjectsToModify"); | |
for(JsonNode element : listOfObjectsToModify) { | |
if (element.getNodeType() == JsonNodeType.OBJECT) { | |
ObjectNode objElement = (ObjectNode) element; | |
objElement.put("extraCrap", "yay!"); | |
objElement.put("timestamp", LocalDateTime.now().toString()); | |
} | |
} | |
System.out.println(mapper.writeValueAsString(rootNode)); | |
} | |
/* toModify.json: ------------------------------------------ | |
{ | |
"someProperty": 1.3, | |
"someOtherProperty": "foo", | |
"otherCrap": true, | |
"listOfObjectsToModify": [ | |
{ "id": 1, "value": "foo" }, | |
{ "id": 2, "value": "bar" }, | |
{ "id": 3, "value": { "someNestedCrap": "baz" } } | |
] | |
} | |
----------------------------------------------------------- */ | |
/* Output: ------------------------------------------------ | |
{ | |
"someProperty" : 1.3, | |
"someOtherProperty" : "foo", | |
"otherCrap" : true, | |
"listOfObjectsToModify" : [ { | |
"id" : 1, | |
"value" : "foo", | |
"extraCrap" : "yay!", | |
"timestamp" : "2017-11-15T20:38:53.760" | |
}, { | |
"id" : 2, | |
"value" : "bar", | |
"extraCrap" : "yay!", | |
"timestamp" : "2017-11-15T20:38:53.766" | |
}, { | |
"id" : 3, | |
"value" : { | |
"someNestedCrap" : "baz" | |
}, | |
"extraCrap" : "yay!", | |
"timestamp" : "2017-11-15T20:38:53.766" | |
} ] | |
} | |
---------------------------------------------------- */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment