Gson is Java JSON library that is used to convert Java object to/from JSON
GSON is developed by google.
GSON Maven dependency is as below
1 2 3 4 5 6 | <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --> <dependency> <groupid>com.google.code.gson</groupid> <artifactid>gson</artifactid> <version>2.8.5</version> </dependency> |
You can also download Gson Jar from here
Gson jar contains API to work with JSON
GOal of GSON is provide simple methods to convert and receive JSON, Provides extensive support for Generics, support complex objects
GSON provides simple functions to convert in to JSON it has toJSON()
and from JSON to Java Object it has fromJSON()
Creating JSON Object
1. Gson gson=new Gson();
2. GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson1 = gsonBuilder.create();
Here Gson()
is no argument constructor that will create Gson object.
Using GsonBuilder
by calling create()
we get Gson object
Converting Java to JSON value
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 | package jsonpkg; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; public class GsonExample { public static void main(String[] args) { int a = 5; double d = 45.44; String name = "Rama"; int[] age = {23, 22, 25, 26, 27, 30}; double[] price = {34.33, 55.43, 51.33, 54.22, 77.00}; List<String> names = new ArrayList<String>(); names.add("Ram"); names.add("Mohan"); names.add("Sohan"); Set<String> branch = new HashSet<String>(); branch.add("Computer Science"); branch.add("Electronics and TeleCommunications"); branch.add("Civil Engg"); Map map = new HashMap(); map.put(1, "Computer"); map.put(2, "Printer"); map.put(3, "Scanner"); Gson gson = new Gson(); System.out.println("JSON of a =" + gson.toJson(a)); System.out.println("JSON of d =" + gson.toJson(d)); System.out.println("JSON of name =" + gson.toJson(name)); System.out.println("JSON of age =" + gson.toJson(age)); System.out.println("JSON of price =" + gson.toJson(price)); GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson1 = gsonBuilder.create(); System.out.println("JSON of names =" + gson1.toJson(names)); System.out.println("JSON of branch =" + gson1.toJson(branch)); System.out.println("JSON of map =" + gson1.toJson(map)); } } |
Result:
1 2 3 4 5 6 7 8 | JSON of a =5 JSON of d =45.44 JSON of name ="Rama" JSON of age =[23,22,25,26,27,30] JSON of price =[34.33,55.43,51.33,54.22,77.0] JSON of names =["Ram","Mohan","Sohan"] JSON of branch =["Civil Engg","Computer Science","Electronics and TeleCommunications"] JSON of map ={"1":"Computer","2":"Printer","3":"Scanner"} |
Some times JSON is difficult to read to make JSON readable .setPrettyPrinting()
can be used as below
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson1= gsonBuilder.setPrettyPrinting().create();
Replace line 40 of program with second line of above code.
Then output is as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | JSON of a =5 JSON of d =45.44 JSON of name ="Rama" JSON of age =[23,22,25,26,27,30] JSON of price =[34.33,55.43,51.33,54.22,77.0] JSON of names =[ "Ram", "Mohan", "Sohan" ] JSON of branch =[ "Civil Engg", "Computer Science", "Electronics and TeleCommunications" ] JSON of map ={ "1": "Computer", "2": "Printer", "3": "Scanner" } |
Serializing a custom object
Here a student class is defined it contains Address class. Create object of student and serializing it as below
Student.java
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 50 51 52 53 54 55 56 57 58 59 | package jsonpkg; public class Student { private long rollNo; private String fname; private String lname; private String branch; private Address address; public Student(long rollNo, String fname, String lname, String branch, Address address) { this.rollNo = rollNo; this.fname = fname; this.lname = lname; this.branch = branch; this.address = address; } public long getRollNo() { return rollNo; } public void setRollNo(long rollNo) { this.rollNo = rollNo; } public String getFname() { return fname; } public void setFname(String fname) { this.fname = fname; } public String getLname() { return lname; } public void setLname(String lname) { this.lname = lname; } public String getBranch() { return branch; } public void setBranch(String branch) { this.branch = branch; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } } |
Address.java
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 | package jsonpkg; public class Address { private String street; private String city; private String state; private long zip; public Address(String street, String city, String state, long zip) { this.street = street; this.city = city; this.state = state; this.zip = zip; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public long getZip() { return zip; } public void setZip(long zip) { this.zip = zip; } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | package jsonpkg; import com.google.gson.Gson; public class GsonExample2 { public static void main(String[] args) { Address address = new Address("Lake view street", "Bhopal", "MP", 12322); Student student = new Student(1, "Ram", "Kumar", "CSE", address); Gson gson = new GsonBuilder().setPrettyPrinting().create(); System.out.println(gson.toJson(student)); } } |
Result
1 2 3 4 5 6 7 8 9 10 11 12 | { "rollNo": 1, "fname": "Ram", "lname": "Kumar", "branch": "CSE", "address": { "street": "Lake view street", "city": "Bhopal", "state": "MP", "zip": 12322 } } |
Reading Json Data from file
Parsing JSON to Java is prerformed as here.
We have saved JSON of a student (same as above structure few parameter changed) in student.json file then we are reading its content from student.json.
student = gson.fromJson(new FileReader(“d://student.json”), Student.class);
To read file from student.json File reader is used. after reading file it is converted to Student type.
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 jsonpkg; import com.google.gson.Gson; import java.io.FileNotFoundException; import java.io.FileReader; public class GsonRead { public static void main(String[] args) { Gson gson = new Gson(); Student student = null; try { student = gson.fromJson(new FileReader("d://student.json"), Student.class); } catch (FileNotFoundException ex) { ex.printStackTrace(); } System.out.println("Received Student Data"); System.out.println("Roll No " + student.getRollNo()); System.out.println("First Name " + student.getFname()); System.out.println("Last Name " + student.getLname()); System.out.println("Branch " + student.getBranch()); System.out.println("Address " + student.getAddress().getStreet() + " " + student.getAddress().getCity() + " " + student.getAddress().getState() + " " + student.getAddress().getZip()); } } |
Result
1 2 3 4 5 6 | Received Student Data Roll No 2 First Name Mohan Last Name Kumar Branch CSE Address Street 5 sector 10 Bhilai CG 232112 |
Reading JSON data from URL
- Open Connection with url
- Read Data using InputStreamReader
- Pass InputStreamReader to fromJson()
1 2 3 4 5 | URL url = new URL("http://ebhor.com/examples/a/student.json"); HttpURLConnection httpcon = (HttpURLConnection) url.openConnection(); httpcon.addRequestProperty("User-Agent", "Mozilla/4.76"); InputStreamReader reader = new InputStreamReader(httpcon.getInputStream()); student = new Gson().fromJson(reader, Student.class); |
Working code is as below
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 | package jsonpkg; import com.google.gson.Gson; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class ReadFromUrl { public static void main(String[] args) { Gson gson = new Gson(); Student student = null; try { URL url = new URL("http://ebhor.com/examples/a/student.json"); HttpURLConnection httpcon = (HttpURLConnection) url.openConnection(); httpcon.addRequestProperty("User-Agent", "Mozilla/4.76"); InputStreamReader reader = new InputStreamReader(httpcon.getInputStream()); student = new Gson().fromJson(reader, Student.class); } catch (IOException ex) { ex.printStackTrace(); } System.out.println("Received Student Data"); System.out.println("Roll No " + student.getRollNo()); System.out.println("First Name " + student.getFname()); System.out.println("Last Name " + student.getLname()); System.out.println("Branch " + student.getBranch()); System.out.println("Address " + student.getAddress().getStreet() + " " + student.getAddress().getCity() + " " + student.getAddress().getState() + " " + student.getAddress().getZip()); } } |
@Expose annotation to serialize and de serialize fields
Annotation Export is used to serialize and deserialize fields it is defined in import com.google.gson.annotations.Expose
@Expose(serialize = true, deserialize = true)
is used serialize true represents it has to be serialize same for deserialize. false value is used to not include the field in process of serialize or deserialize.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import com.google.gson.annotations.Expose; public class Student { @Expose(serialize = true, deserialize = true) private long rollNo; @Expose(serialize = true, deserialize = true) private String fname; @Expose(serialize = true, deserialize = true) private String lname; @Expose(serialize = false,deserialize = false) private String branch; @Expose(serialize = true, deserialize = true) private Address address; //getter setter and constructors } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | import com.google.gson.annotations.Expose; public class Address { @Expose(serialize = true, deserialize = true) private String street; @Expose(serialize = true, deserialize = true) private String city; @Expose(serialize = true, deserialize = true) private String state; @Expose(serialize = true, deserialize = true) private long zip; //getter and setter and constructor } |
in main method to create object we have to use GsonBuilder
as below
call a method excludeFieldWithoutExposeAnnotation()
1 2 3 | GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.excludeFieldsWithoutExposeAnnotation(); Gson gson = gsonBuilder.create(); |
ExclusionStrategy Interface
This interface is also used to exclude any field in serializing and deserialization.
To implement ExcludeStrategy a class has to implement this.
Below is an example to remove fname field from serialization
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | package jsonpkg; import com.google.gson.ExclusionStrategy; import com.google.gson.FieldAttributes; public class MyExclusionStrategy implements ExclusionStrategy { public boolean shouldSkipField(FieldAttributes f) { if (f.getName().equals("fname")) { return true; } return false; } public boolean shouldSkipClass(Class aClass) { return false; } } |
To create Gson object use GsonBuilder as below
1 | Gson gson1 = new GsonBuilder().setExclusionStrategies(new MyExclusionStrategy()).create(); |