Skip to content

Instantly share code, notes, and snippets.

@sanjeevshrestha
Created March 31, 2017 20:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sanjeevshrestha/2d3205de95bfd4a609f98298bb1f9e52 to your computer and use it in GitHub Desktop.
Save sanjeevshrestha/2d3205de95bfd4a609f98298bb1f9e52 to your computer and use it in GitHub Desktop.
Creating JSON with Jackson
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