Skip to content

Instantly share code, notes, and snippets.



Last active Dec 20, 2015
What would you like to do?
Gson gson = new Gson();
System.out.println("A generic object demo");
// a generified object
GenericModel<Integer> model = new GenericModel<>(12);
// converting to json representation
String json = gson.toJson(model);
System.out.println("json representation :" + json);
// converting back to object
Type collectionType = new TypeToken<GenericModel<Integer>>() {
GenericModel<Integer> modelObj =
gson.fromJson(json, collectionType);
System.out.println("converted object representation: " + modelObj);
System.out.println("\nA object from collection framework\n");
// for collection framework objects
List<String> listOfString = new ArrayList<>();
// conversion to json
String jsonStr = gson.toJson(listOfString);
System.out.println("json representation :" + jsonStr);
Type collectionType2 = new TypeToken<List<String>>() {
List<String> listObj = gson.fromJson(jsonStr, collectionType2);
System.out.println("converted object representation: " + listObj);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment