Convert Java objects to JSON strings using gson

Examples from the API:

 Gson gson = new Gson(); // Or use new GsonBuilder().create();
 MyType target = new MyType();
 String json = gson.toJson(target); // serializes target to Json
 MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2

For lists or parameterized types:

 Type listType = new TypeToken<List<String>>() {}.getType();
 List<String> target = new LinkedList<String>();
 target.add("blah");

 Gson gson = new Gson();
 String json = gson.toJson(target, listType);
 List<String> target2 = gson.fromJson(json, listType);

API docs and link for more examples


First of all: there are no "gson" objects. There is just JSON data, strings in a specific format, and the Gson tooling allows you to turn JSON strings into java objects (json parsing), and turning java objects into JSON strings. Coming from there, your request boils down to:

Gson gson = new Gson();
String json = gson.toJson(someInstanceOfStaff);

Beyond that, you should acquire a good tutorial and study this topic, like this one here.

Tags:

Java

Gson