Google%20Gson%20Interview%20Questions%20and%20Answers
Question: What is Versioning Support in Gson?Answer:This is excellent feature you can use, if the class file you are working has been modified in different versions and fields has been annotated with @Since. All you need to do is to use setVersion() method of GsonBuilder. GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(Date.class, new DateSerializer()); gsonBuilder.registerTypeAdapter(Date.class, new DateDeserializer()); //Specify the version like this gsonBuilder.setVersion(1.0); Gson gson = gsonBuilder.create(); Fields added in various versions in Employee.java public class Employee { @Since(1.0) private Integer id; private String firstName; private String lastName; @Since(1.1) private List<String> roles; @Since(1.2) private Date birthDate; //Setters and Getters } Now test the version feature: //Using version 1.0 fields gsonBuilder.setVersion(1.0); Output: { "id":1, "firstName":"Bob", "lastName":"Richardson" } //Using version 1.1 fields gsonBuilder.setVersion(1.1); Output: { "id":1, "firstName":"Bob", "lastName":"Richardson", "roles":["FINANCE","MANAGER"] } //Using version 1.2 fields gsonBuilder.setVersion(1.2); Output: { "id":1, "firstName":"Bob", "lastName":"Richardson", "roles":["FINANCE","MANAGER"], "birthDate":"17/06/2014" } |
Is it helpful?
Yes
No
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?