Created
March 31, 2017 20:08
-
-
Save sanjeevshrestha/2d3205de95bfd4a609f98298bb1f9e52 to your computer and use it in GitHub Desktop.
Creating JSON with Jackson
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
ObjectMapper mapper = new ObjectMapper(); | |
ArrayNode arrayNode = mapper.createArrayNode(); | |
ObjectNode objectNode1 = mapper.createObjectNode(); | |
objectNode1.put("bookName", "Java"); | |
objectNode1.put("price", "100"); | |
ObjectNode objectNode2 = mapper.createObjectNode(); | |
objectNode2.put("bookName", "Spring"); | |
objectNode2.put("price", "200"); | |
ObjectNode objectNode3 = mapper.createObjectNode(); | |
objectNode3.put("bookName", "Liferay"); | |
objectNode3.put("price", "500"); | |
arrayNode.add(objectNode1); | |
arrayNode.add(objectNode2); | |
arrayNode.add(objectNode3); | |
/** | |
* We can directly write the JSON in the console. | |
* But it wont be pretty JSON String | |
*/ | |
System.out.println(arrayNode.toString()); | |
/** | |
* To make the JSON String pretty use the below code | |
*/ | |
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(arrayNode)); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment