Saturday, February 10, 2018

google json library to convert from and to json

Google Gson is an open source  java based library developed by Google.
It facilitates serialization of Java objects to JSON and vice versa.

import com.google.gson.Gson;
import java.util.HashMap;
import java.util.Map;
public class FormToGson {
    public FormToGson () {
        super();
    }
    public static void main(String[] args) {
        Map map = new HashMap();
        map.put("Name", "Mahmoud");
        map.put("Job", "DEV");
        Gson gosn = new Gson();
        String paramsJsonString =  gosn.toJson(map);
        System.out.println(paramsJsonString);
       
        HashMap map2 = gosn.fromJson(paramsJsonString, HashMap.class);
        System.out.println(map2.get("Name"));
    }
}
This can be helpful when calling a servlet for example to print a jasper report you will pass only one query parameter that holds the json object as a string from the bean class :
 /Servlet?params=paramsJsonString .

To downlaod the jar:

https://mvnrepository.com/artifact/com.google.code.gson/gson




No comments:

Post a Comment

java - fill distinct objects in ArrayList

If you have a list that contains some objects that it is considered as duplication when two or three fields of these objects are equal. How ...