Google Gson Interview Questions and Answers
The Best LIVE Mock Interview - You should go through before Interview
Freshers / Beginner level questions & answers
Ques 1. What is Google-Gson?
Google Gson is a Java library that can be used to convert Java Objects into respective JSON format. In another way, it can used to convert the JSON into equivalent java objects. There are some other java libraries also capable of doing this conversion, but Gson stands among very few which do not require any pre-annotated java classes OR sourcecode of java classes in any way.
Gson also support the old java classes which had not support of generics in them for type information. It just work with these legacy classes smoothly.
Is it helpful?
Add Comment
View Comments
Ques 2. What are the two ways to create Gson objects?
Gson object can be created in two ways. First way gives you a quick Gson object ready for faster coding, while second way uses GsonBuilder to build a more sophisticated Gson object.
//First way to create a Gson object for faster coding
Gson gson = new Gson();
//Second way to create a Gson object using GsonBuilder
Gson gson = new GsonBuilder()
.disableHtmlEscaping()
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.setPrettyPrinting()
.serializeNulls()
.create();
When using GsonBuilder, there are plenty of other useful options you can provide to Gson object.
Is it helpful?
Add Comment
View Comments
Ques 3. How to convert Java objects to JSON format?
To convert the java objects to JSON format, use toJson() method.
Employee employee = new Employee();
employee.setId(1);
employee.setFirstName("Arindam");
employee.setLastName("Ghosh");
employee.setRoles(Arrays.asList("FINANCE", "MANAGER"));
Gson gson = new Gson();
System.out.println(gson.toJson(employee));
Output:
{
"id":1,
"firstName":"Rob",
"lastName":"Bosch",
"roles":["FIINANCE","MANAGER"]
}
Is it helpful?
Add Comment
View Comments
Ques 4. How to convert JSON to Java Objects?
To convert the JSON to java object, use fromJson() method.
Gson gson = new Gson();
System.out.println(
gson.fromJson("{'id':1,'firstName':'Arindam','lastName':'Ghosh','roles':['FINANCE','MANAGER']}",
Employee.class));
Output:
Employee [id=1, firstName=Arindam, lastName=Ghosh, roles=[FINANCE, MANAGER]]
Is it helpful?
Add Comment
View Comments
Most helpful rated by users:
- What is Google-Gson?
- How to convert Java objects to JSON format?
- What are the two ways to create Gson objects?
- What is Instance Creator? Why and when do we require this?
- How to custom Serialization and De-serialization in Gson?