Monday, 13 May 2013

Jackson data binding –Map & JSON

Jackson data binding –Map & JSON


We show you how to convert user define Map to/from JSON data. Map is more suitable
and easy and short JSON processing.
We will show you how to use Map to construct the JSON data, write it to file, how to read JSON from file,
and display each value via Map.
Step 1: Write JSON to File:

Step 2: Read JSON from a File:

In Jackson, you can use Tree Model to represent JSON, and perform the read and write operations via
JsonNode, it is similar to DOM tree for XML.
ObjectMapper mapper = new ObjectMapper();
BufferedReader fileReader = new BufferedReader(new FileReader("d:\\test\\person.json"));
JsonNode rootNode = mapper.readTree(fileReader);
/*** read value from key "name" ***/
JsonNode nameNode = rootNode.path("name");
System.out.println(nameNode.getTextValue());

No comments:

Post a Comment