Skip to content

Instantly share code, notes, and snippets.

@ajduke
Last active December 20, 2015 08:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajduke/6098716 to your computer and use it in GitHub Desktop.
Save ajduke/6098716 to your computer and use it in GitHub Desktop.
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>>() {
}.getType();
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<>();
listOfString.add("ajduke");
listOfString.add("ajduchess");
// conversion to json
String jsonStr = gson.toJson(listOfString);
System.out.println("json representation :" + jsonStr);
Type collectionType2 = new TypeToken<List<String>>() {
}.getType();
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