Jackson JSON Parser is a very popular JSON Java Parser, which can easily transform Java Objects to JSON and vice versa and Jackson API even provides default mapping for most of the objects which need to be serialized. In my previous articles, we have learnt How to Read a JSON in Java and How to write JSON object to File using GSON and JSON.simple API. In this Jackson JSON Example, let’s see how to use Jackson API to read JSON file and Write a JSON file.
Folder Structure:
-
- Create a new Java Project “JacksonJSONTutorial” and create a package for our src files “com.javainterviewpoint“
- Add the required libraries to the build path. Java Build Path ->Libraries ->Add External JARs and add the below jars.
commons-io-2.5.jar
jackson-core-asl-1.9.13.jar
jackson-mapper-asl-1.9.13.jar
if you are running on maven add the below dependency to your pom.xml
<dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </dependency>
- Create the Java classes Jackson_JSON_Reader.java, Jackson_JSON_Writer.java and UserDetails.java under com.javainterviewpoint folder.
Jackson JSON Example
For our Example of Convert JSON to Java object and Convert Java Object to JSON again. We will be using this JSON file.
JSON file content(test.json)
{ "name" : "JavaInterviewPoint", "age" : 999, "favoriteSports" : [ "Football", "Cricket", "Tennis","Basket Ball"] }
UserDetail.java
A simple POJO, for holding the details of the user.
package com.javainterviewpoint; import java.util.List; public class UserDetails { private String name; private int age; private List favoriteSports; public UserDetails() { super(); } public UserDetails(String name, int age, List favoriteSports) { super(); this.name = name; this.age = age; this.favoriteSports = favoriteSports; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public List getFavoriteSports() { return favoriteSports; } public void setFavoriteSports(List favoriteSports) { this.favoriteSports = favoriteSports; } }
Jackson JSON Reader
package com.javainterviewpoint; import java.io.File; import java.io.IOException; import org.apache.commons.io.FileUtils; import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; public class Jackson_JSON_Reader { public static void main(String[] args) { String data=""; //Create a new ObjectMapper, for mapping data to POJO ObjectMapper mapper = new ObjectMapper(); try { //Read the test.json data = FileUtils.readFileToString(new File("c:\\test.json")); //Read and map data to userDetails object UserDetails userDetails = mapper.readValue(data, UserDetails.class); //Print the userdetails System.out.println("*** User Details ***"); System.out.println("User Name : "+userDetails.getName()); System.out.println("User Age : "+userDetails.getAge()); System.out.println("Favourite Sports : "); for(String fav : userDetails.getFavoriteSports()) { System.out.print(fav +" | "); } } catch (JsonParseException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
-
-
- Create a new ObjectMapper object, it helps us mapping the JSON data with the POJO
-
ObjectMapper mapper = new ObjectMapper();
-
-
- Using the apache commons.io, read the “test.json” file. You can also read the file with any Java File Reader such as BufferedReader
-
data = FileUtils.readFileToString(new File("c:\\test.json"));
-
-
- The readValue() method of the ObjectMapper class converts the JSON String into Java Object and maps it to the POJO. It takes two parameters data (JSON String) and the POJO class(UserDetails.class)
-
UserDetails userDetails = mapper.readValue(data, UserDetails.class);
-
-
- Finally, print the user details
-
System.out.println("*** User Details ***"); System.out.println("User Name : "+userDetails.getName()); System.out.println("User Age : "+userDetails.getAge()); System.out.println("Favourite Sports : "); for(String fav : userDetails.getFavoriteSports()) { System.out.print(fav +" | "); }
Output :
Jackson JSON Writer
package com.javainterviewpoint; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.codehaus.jackson.map.ObjectMapper; public class Jackson_JSON_Writer { public static void main(String[] args) { try { //Create a new UserDetails object UserDetails userDetails = new UserDetails(); //set value to its properties userDetails.setName("Java"); userDetails.setAge(111); List favoriteSports = new ArrayList(); favoriteSports.add("BaseBall"); favoriteSports.add("Hockey"); favoriteSports.add("Table Tennis"); userDetails.setFavoriteSports(favoriteSports); //Create a new ObjectMapper, for mapping data to POJO ObjectMapper mapper = new ObjectMapper(); //Set prettyprint option mapper.writerWithDefaultPrettyPrinter(); //Write the userdetails data into test1.json mapper.writeValue(new File("c://Jackson//test1.json"), userDetails); System.out.println("JSON Write successful!!"); } catch (IOException e) { e.printStackTrace(); } } }
-
-
- Create a new Object for the UserDetails class
-
UserDetails userDetails = new UserDetails();
-
-
- Set value to the properties of UserDetails
-
userDetails.setName("Java"); userDetails.setAge(111); List favoriteSports = new ArrayList(); favoriteSports.add("BaseBall"); favoriteSports.add("Hockey"); favoriteSports.add("Table Tennis"); userDetails.setFavoriteSports(favoriteSports);
-
-
- Create a new ObjectMapper object, it helps us mapping the JSON data with the POJO
-
ObjectMapper mapper = new ObjectMapper();
-
-
- Using the writeValue() method of the ObjectMapper class, write the userDetails object into test1.json.
-
mapper.writeValue(new File("c://test1.json"), userDetails);
Output :
{"name":"Java","age":111,"favoriteSports":["BaseBall","Hockey","Table Tennis"]}
@JSONView Annotation
@JSONView is supported since Jackson 1.4, this will give the control of displaying the entities to the user.
First, we need to create our view class, it has three static classes NameOnly (For displaying name alone), AgeOnly (for displaying age alone), AgeAndFavSports (for displaying both Age and Favourite Sports)
package com.javainterviewpoint; public class Views { public static class NameOnly{}; public static class AgeOnly{}; public static class AgeAndFavSports extends AgeOnly {}; }
Now our POJO will be having the @JSONView annotation on it.
package com.javainterviewpoint; import java.util.List; import org.codehaus.jackson.map.annotate.JsonView; public class UserDetails { @JsonView(Views.NameOnly.class) private String name; @JsonView(Views.AgeOnly.class) private int age; @JsonView(Views.AgeAndFavSports.class) private List favoriteSports; public UserDetails() { super(); } public UserDetails(String name, int age, List favoriteSports) { super(); this.name = name; this.age = age; this.favoriteSports = favoriteSports; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public List getFavoriteSports() { return favoriteSports; } public void setFavoriteSports(List favoriteSports) { this.favoriteSports = favoriteSports; } }
@JSONView Example
package com.javainterviewpoint; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.codehaus.jackson.JsonGenerationException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; import org.codehaus.jackson.map.SerializationConfig; public class JSONView_Example { public static void main(String[] args) { try { ObjectMapper mapper = new ObjectMapper(); //By default all fields without explicit view definition are included, disable this mapper.configure(SerializationConfig.Feature.DEFAULT_VIEW_INCLUSION, false); UserDetails userDetails = new UserDetails(); userDetails.setName("Java"); userDetails.setAge(111); List favoriteSports = new ArrayList(); favoriteSports.add("BaseBall"); favoriteSports.add("Hockey"); favoriteSports.add("Table Tennis"); userDetails.setFavoriteSports(favoriteSports); String jsonString; //Displaying Name alone jsonString = mapper.writerWithView(Views.NameOnly.class).writeValueAsString(userDetails); System.out.println("** Name Only View **"); System.out.println(jsonString); //Displaying Age alone jsonString = mapper.writerWithView(Views.AgeOnly.class).writeValueAsString(userDetails); System.out.println("** Age Only View **"); System.out.println(jsonString); //Displaying Both Age and FavouriteSports jsonString = mapper.writerWithView(Views.AgeAndFavSports.class).writeValueAsString(userDetails); System.out.println("** Age and FavouriteSports View **"); System.out.println(jsonString); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
Output :
When we execute the JSONView_Example class, we will be getting the below output
** Name Only View ** {"name":"Java"} ** Age Only View ** {"age":111} ** Age and FavouriteSports View ** {"age":111,"favoriteSports":["BaseBall","Hockey","Table Tennis"]}
Leave a Reply