GOOGLE-Gson Tutorial

Json is a JavaScript ObjectNotation, very useful for handling web content and API request, serializing data is very common and practical specially for network applications.

This is how we can serialize and deserialize Objects to a Json Format:

  • Get the last version of Gson from here.
  • Create a Java project in Eclipse and add the gson-2.3.1.jar to the classpath. (how to do it–> here)
  • Now we create a Class, in this case Animal
  • public class Animal {

    private String name;
    private boolean extinted;
    private int eyes;
    public Animal(String name, boolean extinted, int eyes) {
    this.name = name;
    this.extinted = extinted;
    this.eyes = eyes;
    }

  • create a Method for the serialization:
  • public String toJson() {

final Gson gson = new Gson();
return gson.toJson(this, this.getClass());
}

  • test the serialization:
  • public static void main(String[] args)    {

Animal animal = new Animal(„spider“, false, 8);
System.out.println(animal.toJson());
animal = new Animal(„T-Rex“, true, 2);
System.out.println(animal.toJson());

}

verify the results:

{„name“:“spider“,“extinted“:false,“eyes“:8}
{„name“:“T-Rex“,“extinted“:true,“eyes“:2}

Hinterlasse einen Kommentar