Analysis Of Jackson And Gson
- General
Analysis Of Jackson And Gson
In this blog we will read about the Gson and Jackson Libraries which are used to convert JSON data to Java Object and vice-versa.
Gson is the open source Java Library provided by Google. If we have to use Gson then we have to import the dependency of it whereas there is no need to import the dependency of Jackson when we are working with Spring Boot.
-> Serialization And Deserialization :
Steps of processing the data for the conversion ->
1. Add the Dependency to XML file :
Firstly, add the Gson dependency to the pom.xml file to create an object of Gson and use its features.
1 2 3 4 5 |
<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.9</version> </dependency> |
If you are not using Spring Boot then for using Jackson you have to add Jackson Dependency.
1 2 3 4 5 |
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.13.1</version> </dependency> |
2. Tree Model:
It prepares an in-memory tree representation of the JSON document. It builds a tree of JsonObject nodes.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
package com.example.demo.model; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class User { public User(String name, int age) { this.name = name; this.age = age; } private String name; private int age; } |
3. Data Binding :
It converts JSON to and from POJO (Plain Old Java Object) using a property accessor.
-
Serialization :
(i) Conversion of data from the Java Object to the JSON is known as serialization.
(ii) By performing serialization we pass the object of the model as a parameter of the Gson or Jackson method which converts to JSON String.
(a) By using Gson :
Firstly, we will create a GSON Object and then we directly use a method toJson() which converts the data from Java Object to JSON String.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.core.io.ClassPathResource; import com.example.demo.model.User; import com.google.gson.Gson; @SpringBootApplication public class ComparativeAnalysisOfJacksonAndGsonApplication { public static void main(String[] args) { SpringApplication.run(ComparativeAnalysisOfJacksonAndGsonApplication.class, args); getJson(new User("Anaya", 21)); } public static void getJson(User user) { Gson gson = new Gson(); String json = gson.toJson(user); System.out.println(json); } } |
(b) By using Jackson :
We will create an object of mapper class and then use the method for converting to JSON format which should be in try-catch block or should throw an exception.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.example.demo.model.User; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; @SpringBootApplication public class ComparativeAnalysisOfJacksonAndGsonApplication { public static void main(String[] args) { SpringApplication.run(ComparativeAnalysisOfJacksonAndGsonApplication.class, args); getJson(new User("Anaya", 21)); } public static void getJson(User user) { ObjectMapper mapper = new ObjectMapper(); String json = null; try { json = mapper.writeValueAsString(user); } catch (JsonProcessingException e) { e.printStackTrace(); } System.out.println(json); } } |
Output :
Note : The output for Gson and Jackson are same.
1 |
{"name":"Anaya","age":21} |
-
Deserialization :
(i) Conversion of data from the JSON to the JAVA Object is known as deserialization.
(ii) By performing deserialization we have to pass the Json element and class of tree model as parameters to perform conversion from Json string to Java Object.
(a) By using Gson :
After creating the object of the Gson we will use the fromJson() method to convert the data into Java Object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.example.demo.model.User; import com.google.gson.Gson; @SpringBootApplication public class ComparativeAnalysisOfJacksonAndGsonApplication { public static void main(String[] args) { SpringApplication.run(ComparativeAnalysisOfJacksonAndGsonApplication.class, args); getJson(new User("Anaya", 21)); } public static void getJson(User user) { Gson gson = new Gson(); String json = gson.toJson(user); System.out.println("Output in the form of Jason String"); System.out.println(json); System.out.println(); getObj(json); } public static void getObj(String json) { Gson gson = new Gson(); User user = gson.fromJson(json, User.class); System.out.println("Output in the form of Java Object"); System.out.println(user.getName()); System.out.println(user.getAge()); } } |
(b) By using Jackson :
After creating the object of the Jackson we will use thereadValue() method to convert the data into Java Object which is surrounded by the try-catch block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.example.demo.model.User; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; @SpringBootApplication public class ComparativeAnalysisOfJacksonAndGsonApplication { public static void main(String[] args) { SpringApplication.run(ComparativeAnalysisOfJacksonAndGsonApplication.class, args); getJson(new User("Anaya", 21)); } public static void getJson(User user) { ObjectMapper mapper = new ObjectMapper(); String json = null; try { json = mapper.writeValueAsString(user); } catch (JsonProcessingException e) { e.printStackTrace(); } System.out.println("Output in the form of Json String"); System.out.println(json); System.out.println(); getObj(json); } public static void getObj(String json) { ObjectMapper mapper = new ObjectMapper(); User user = null; try { user = mapper.readValue(json, User.class); } catch (JsonMappingException e) { e.printStackTrace(); } catch (JsonProcessingException e) { e.printStackTrace(); } System.out.println("Output in the form of Java Object"); System.out.println(user.getName()); System.out.println(user.getAge()); } } |
Output :
Note : The output for Gson and Jackson are same.
1 2 3 4 5 6 |
Output in the form of Json String {"name":"Anaya","age":21} Output in the form of Java Object Anaya 21 |
-> Limitations :
1. If we are using Jackson then we have to use a try-catch block or throw an Exception.
2. Lines of code are more in Jackson.
-> Note :
Other features provided by Gson and Jackson are:
1. Nested Objects :
- Firstly, add the respective dependencies.
- Create the Tree Model :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
/* Model Of User */ package com.example.demo.model; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class User { public User(String name, int age, Address address) { this.name = name; this.age = age; this.address = address; } private String name; private int age; private Address address; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
/* Model Of Address */ package com.example.demo.model; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Getter @Setter @NoArgsConstructor @AllArgsConstructor public class Address { public Address(String country, String city) { this.country = country; this.city = city; } private String country; private String city; } |
- Data Binding for nested objects is the same as we did for the simple objects. But now we have to pass the object of the nested class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.example.demo.model.Address; import com.example.demo.model.User; import com.google.gson.Gson; @SpringBootApplication public class ComparativeAnalysisOfJacksonAndGsonApplication { public static void main(String[] args) { SpringApplication.run(ComparativeAnalysisOfJacksonAndGsonApplication.class, args); getJson(new User("Anaya", 21, new Address("India", "Jaipur"))); } public static void getJson(User user) { Gson gson = new Gson(); String json = gson.toJson(user); System.out.println("Output in the form of Jason String"); System.out.println(json); System.out.println(); getObj(json); } public static void getObj(String json) { Gson gson = new Gson(); User user = gson.fromJson(json, User.class); System.out.println("Output in the form of Java Object"); System.out.println(user.getName()); System.out.println(user.getAge()); System.out.println(user.getAddress().getCountry()); System.out.println(user.getAddress().getCity()); } } |
- Similarly we can do for Jackson also.
Output :
Note : The output for Gson and Jackson are same.
1 2 3 4 5 6 7 8 |
Output in the form of Json String {"name":"Anaya","age":21,"address":{"country":"India","city":"Jaipur"}} Output in the form of Java Object Anaya 21 India Jaipur |
2. Read JSON File :
- Previously we were passing the Json String as an input but now we are passing the Json File.
- Firstly create a .json file in the resource folder.
1 2 3 4 5 6 7 8 |
{ "name":"Anaya", "age":21, "address":{ "country":"India", "city":"Jaipur" } } |
- Then we find the path of the Json file by creating the File Object.
- After that when we call the method fromJson() then in place of passing the json String we pass the object of the FileReader with the file path as the parameter. And the rest part is the same.
- Similarly we can do Jackson also.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
package com.example.demo; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.core.io.ClassPathResource; import com.example.demo.model.User; import com.google.gson.Gson; import com.google.gson.JsonIOException; import com.google.gson.JsonSyntaxException; @SpringBootApplication public class ComparativeAnalysisOfJacksonAndGsonApplication { public static void main(String[] args) { SpringApplication.run(ComparativeAnalysisOfJacksonAndGsonApplication.class, args); try { File file = new ClassPathResource("Data.json").getFile(); readFile(file.toString()); } catch (IOException e) { e.printStackTrace(); } } public static void readFile(String fileAddress) { Gson gson = new Gson(); User user = null; try { user = gson.fromJson(new FileReader(fileAddress), User.class); } catch (JsonSyntaxException e) { e.printStackTrace(); } catch (JsonIOException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } System.out.println("Output in the form of Java Object"); System.out.println(user.getName()); System.out.println(user.getAge()); System.out.println(user.getAddress().getCountry()); System.out.println(user.getAddress().getCity()); } } |
3. Write JSON File :
- In this we are storing the output of Json String in a separate file.
- We will use the FileWriter to write the output in the file.
- We will pass the object of the tree model in the method.
- Then in the object of the FileWriter we pass the path where we want to add our file.
- After writing in the file, we have to close the writer object.
- Similarly we can do for Jackson also.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
package com.example.demo; import java.io.FileWriter; import java.io.IOException; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.example.demo.model.Address; import com.example.demo.model.User; import com.google.gson.Gson; @SpringBootApplication public class ComparativeAnalysisOfJacksonAndGsonApplication { public static void main(String[] args) { SpringApplication.run(ComparativeAnalysisOfJacksonAndGsonApplication.class, args); writeFile(new User("Anaya", 21, new Address("India", "Jaipur"))); } public static void writeFile(User user) { Gson gson = new Gson(); try { FileWriter fileWriter = new FileWriter("/home/auriga/Documents/workspace-spring-tool-suite-4-4.13.1.RELEASE/Comparative-Analysis-of-Jackson-and-Gson/src/main/resources/NewData.json"); System.out.println("File created"); gson.toJson(user, fileWriter); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } } |
4. JsonIgnore , JsonIgnoreProperties And JsonIgnoreType :
- This works only with Jackson not with Gson.
-> JsonIgnoreProperties :
- It is used to ignore the specified logical properties.
- It is annotated at the class level.
- We write the @JsonIgnoreProperties in the Tree Model.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package com.example.demo.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; @JsonIgnoreProperties(value = { "name" }) public class User { private String name; private int age; public User(String name, int age) { this.name = name; this.age = age; } 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; } } |
- Then our main method looks like :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.example.demo.model.User; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; @SpringBootApplication public class ComparativeAnalysisOfJacksonAndGsonApplication { public static void main(String[] args) { SpringApplication.run(ComparativeAnalysisOfJacksonAndGsonApplication.class, args); getJson(new User("Anaya", 21)); } public static void getJson(User user) { ObjectMapper mapper = new ObjectMapper(); String json = null; try { json = mapper.writeValueAsString(user); } catch (JsonProcessingException e) { e.printStackTrace(); } System.out.println(json); } } |
-
Output :
1 |
{"age":21} |
-> JsonIgnore :
- It is used to ignore the specified logical properties.
- It can be used with Getter, Setter, Field.
- The only difference is in the Tree Model and the main function remains same as of JsonIgnoreProperties.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
package com.example.demo.model; import com.fasterxml.jackson.annotation.JsonIgnore; public class User { @JsonIgnore private String name; private int age; public User(String name, int age) { this.name = name; this.age = age; } 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; } } |
-
Output :
1 |
{"age":21} |
-> JsonIgnoreType :
- It is annotated at the class level.
- It is used to ignore the complete class.
- In the below example we are writing @JsonIgnoreType to the nested Information class due to which the whole Information class gets ignored.
- No change in main function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
package com.example.demo.model; import com.fasterxml.jackson.annotation.JsonIgnoreType; public class User { private String name; private Information information; public User(String name, Information information) { this.name = name; this.information = information; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Information getInformation() { return information; } public void setInformation(Information information) { this.information = information; } @JsonIgnoreType public static class Information{ private int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Information(int age) { this.age = age; } } } |
-
Output :
1 |
{"name":"Anaya"} |
Related content
Auriga: Leveling Up for Enterprise Growth!
Auriga’s journey began in 2010 crafting products for India’s