Mícéal Gallagher in String 4 minutes

Java - Using Google GSON

This indispensable library has brought me a great deal of joy when it comes to json-ifying objects and primitives.

Variable data to JSON

No complexity here when it comes to Strings:

```javaGson gson = new Gson(); String data = “One string to rule them all”; // json = “One string to rule them all” String json = gson.toJson(data);


An array of integers requires you to tell Gson what it's converting:

```javaGson gson = new Gson();
int[] integers = new []{ 2, 7, 10 };
// json = [1,1,2,3,5,8,13]
String json = gson.toJson(integers, int[].class);

What about complex objects? Gson takes care of that as well.

```javaGson gson = new Gson(); Person person = new Person(); // json = {“name”:”Miceal Gallagher”,”age”:27} String json = gson.toJson(person, Person.class);


If you have an collection of persons you can use Gson like so:

```javaGson gson = new Gson();
ArrayList<Person> people = new ArrayList<Person>();
people.add( new Person() );
people.add( new Person() );
Type type = new TypeToken<List<Person>>(){ /**/ }.getType();
json = gson.toJson( people, type );
Person person = new Person();

// json = {“name”:”Miceal Gallagher”,”age”:27} String json = gson.toJson(person, Person.class);

JSON to variable data

And what if you need to go from Json to the data. Well if it’s JSON that contains a simple string:

```javaGson gson = new Gson(); String json = “"One string to rule them all"”; String data = gson.fromJson(json, String.class); System.out.println(“Value: “ + data);


If you have an array of integers:

```javaGson gson = new Gson();
String json = "[1, 1, 2, 3, 5, 8, 13]";
int[] integers = gson.fromJson(json, int[].class);

If you have a “complex” object:

```javaGson gson = new Gson(); json = “{"name":"Miceal Gallagher","age":27}”; Person person = gson.fromJson(json, Person.class);


Finally if you have an array of "complex" objects:

```javaGson gson = new Gson();
json = "[{\"name\":\"Miceal Gallagher\",\"age\":27},{\"name\":\"Miceal Gallagher\",\"age\":27}]";
Type type = new TypeToken<List<Person>>(){ /**/ }.getType();
List<Person> people = gson.fromJson(json, type);

Conculsion

Gson is a powerful easy to use JSON library. My JSON requirements have been very typical of any client-sever stack and it has yet to let me down. Get the code on GitHub References: google-gson Gson User Guide