Saturday, October 22, 2016

Serialization and Deserialization JSON in JAVA with GSON


Today I will give an example of using GSON to Serialization and Deserialization JSON in JAVA

When we work with JSON, there are some tasks we usually do,

  1. Parse Object to JSON and vice versa
  2. Parse Collection to JSON and vice versa
  3. And sometime we need to create an JSON object with dynamic field, In my example I used Map to do it.We also need to Deserialization and JSON object with dynamic field to Java Object

Here is some code example:


import java.awt.Point;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

 * @author ducnguyen
public class Main {

    private static Gson gson = new Gson();

    public static void main(String[] args) {
        System.out.println("Serialization and Deserialization an OBJECT");
        Point p1 = new Point(2, 1);
        String json1 = gson.toJson(p1);
        System.out.println("p1 -> json1 : " + json1);
        Point p2 = gson.fromJson(json1, Point.class);
        System.out.println("json1 -> p2 : " + p2.toString());

        System.out.println("Serialization and Deserialization a LIST");
        List l1 = Arrays.asList(new Point(2, 1), new Point(3, 4));
        String json2 = gson.toJson(l1);
        System.out.println("l1 -> json2 : " + json1);
        List l2 = gson.fromJson(json2, List.class);
        System.out.println("json2 -> l2 : " + l2.toString());

        System.out.println("Create object fields with MAP");
        Map jsonObject = new HashMap<>();
        jsonObject.put("integer", 100);
        jsonObject.put("string", "hello world");
        jsonObject.put("boolean", Boolean.TRUE);
        String json3 = gson.toJson(jsonObject);
        System.out.println("jsonObject -> json3 : " + json3);
        System.out.println("Deserialization MAP");
        Map jsonObject2 = gson.fromJson(json3, Map.class);
        System.out.println("json3 -> jsonObject2 : "+ jsonObject2.toString());



Here is output of the code:

Serialization and Deserialization an OBJECT
p1 -> json1 : {"x":2,"y":1}
json1 -> p2 : java.awt.Point[x=2,y=1]
Serialization and Deserialization a LIST
l1 -> json2 : {"x":2,"y":1}
json2 -> l2 : [{x=2.0, y=1.0}, {x=3.0, y=4.0}]
Create object fields with MAP
jsonObject -> json3 : {"integer":100,"string":"hello world","boolean":true}
Deserialization MAP
json3 -> jsonObject2 : {integer=100.0, string=hello world, boolean=true}

You can download source code here