We will cover how to use Gson to convert JSON into Java Object and Java Object into JSON in the following points

  • Overview
  • Use Gson – Maven/Gradle
  • Object to JSON
  • JSON to Object
  • TypeToken
  • Custom variables naming
  • JSON with HTML content
  • JSON in Readable format
  • Fields from JSON
  • Include Null Fields
  • Gson is a Java library that can be used to convert Java Objects into their JSON representation.
  • It can also be used to convert a JSON string to an equivalent Java object.
Use Gson – Maven/Gradle
  • Gradle
dependencies {
implementation 'com.google.code.gson:gson:2.8.5'
  • Maven:

You can get the latest version of Maven here.

Convert Object to JSON
class Example {
private int value1 = 12;
private String value2 = "abc";
Example() {}

// Serialize it: Convert Object to JSON
Example obj = new Example();
Gson gson = new Gson();
String json = gson.toJson(obj);

OUTPUT ===> {"value1":12,"value2":"abc"}
Convert JSON to Object
Example obj2 = gson.fromJson(json, Example.class);
Few Points:
  • All fields in the current class (and from all superclasses) are included for serialization and deserialization by default.
  • If a field is marked transient, (by default) it is ignored and not included in the JSON serialization or deserialization.
  • While serializing, a null field is omitted from the output.
  • While deserializing, a missing entry in JSON results in setting the corresponding field in the object to its default value: null for object types, zero for numeric types, and false for booleans.
Using TypeToken
  • Gson uses Java reflection API to get the type of the object to which a JSON text is to be mapped.
  • But with generics, this information is lost during serialization.
  • To counter this problem, Gson provides a class com.google.gson.reflect.TypeToken to store the type of the generic object.
Gson gson = new Gson();
Type type = new TypeToken<List<User>>(){}.getType();
vpnStatusList=gson.fromJson(result, type);
Add Custom variables naming
  • Let’s say our Json is something like this.
"src-switch" : "1255",
"src-port" : "2255",
"dst-switch" : "2255",
"dst-port" : "2255"
  • In normal case to convert this String to Object we need to have Java Object class
    with variables names like “src-switch“.
  • But in Java, this format is not valid naming Convention.
  • To handle this we can use @SerializedName and give the attr-name available in JSON.
public class LinksDetailsData {

private String srcswitch;

private String srcport;
private String destswitch;
private String destport;
private String type;

Gson gson = new Gson();
LinksDetailsData = gson.fromJson(jsonString, LinksDetailsData.class);
Convert JSON with HTML content
  • Let’s take this Java Object as example
Class MyData {

private String data = "<div>Hello Wolrd</div> <p>Hello</p>";
private String status = "Active";

If we convert this into JSON String

Gson gson = new Gson();
String jsonInString = gson.toJson(data);
  • The output might not be as expected. It might contain some characters. Like “<” into \033
  • To resolve this we need to tell Gson to disable Html Escaping.
  • Like this
Gson gson = new GsonBuilder().disableHtmlEscaping().create();
String jsonInString = gson.toJson(data);
Print JSON in Readable format

Gson gson = new GsonBuilder().setPrettyPrinting().create();

// will print this


// as

"brand": "Rover",
"doors": 5
Excluding Fields from JSON
  • Transient Fields
public class Car {
public transient String brand = "Test"; // ignore this field in JSON
public int doors = 0;
  • The @Expose Annotation
    • The GSON @Expose annotation (com.google.gson.annotations.Expose) can be used to mark a field to be exposed or not (included or not) when an object is serialized or deserialized.
@Expose(serialize = true);
@Expose(serialize = false);
@Expose(deserialize = true);
@Expose(deserialize = false);
@Expose(serialize = true , deserialize = false);
@Expose(serialize = false, deserialize = true);
  • In order to get GSON to react to the @Expose annotations, you must create a Gson instance using the GsonBuilder class. Here is how that looks:
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
  • Note, that this configuration makes GSON ignore all fields that do not have an @Expose annotation.
  • To have a field included in serialization or deserialization it must have an @Expose annotation above it.
Include Null Fields in JSON
GsonBuilder builder = new GsonBuilder();
builder.serializeNulls(); // include null variables
Gson gson = builder.create();
Car car = new Car();
car.brand = null;
String json = gson.toJson(car);
Gson gson = new GsonBuilder()
.registerTypeAdapter(Id.class, new IdTypeAdapter())
Categories: JAVA


Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *