Parsing Java Objects Into JSON String
GSON Api consists a Class named Gson in the package 'com.google.gson' which contains a method named toJson() with that method we can parse Java Object to Json String .
fromJson() method is available with various signatures lets view those
String toJson(JsonElement jsonElement) String toJson(Object src) String toJson(Object src, Type typeOfSrc) void toJson(Object src, Type typeOfSrc, JsonWriter writer) void toJson(Object src, Type typeOfSrc, Appendable writer)
To explain the concept I am taking a class named Player with the following structure and I will use this for most of the examples.
/** * @author TutorialToUs.com */ package com.tutorialtous.gson; import java.util.LinkedList; import java.util.List; import com.google.gson.annotations.Since; public class Player { public String name; public String email = null; public String gender; public int age; public List<String> gamesplayed = new LinkedList<>(); }
Now I want to parse this Java Object into Json String using Gson.
/** * @author TutorialToUs.com */ package com.tutorialtous.gson; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class ToJsonParsingExample { public static void main(String args[]) { Player obj = new Player(); String jsonString = null; obj.age = 29; obj.name = "Alex"; obj.gender = "Male"; GsonBuilder builder = new GsonBuilder(); builder.excludeFieldsWithoutExposeAnnotation(); Gson gson =builder.create(); jsonString = gson.toJson(obj); System.out.println(jsonString); } }output
{"name":"Alex","gender":"Male","age":29,"gamesplayed":[]}