We will cover how to use Gson to convert JSON into Java Object and Java Object into JSON in 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
Overview
  • 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:
<dependency>
   <groupId>com.google.code.gson</groupId>
   <artifactId>gson</artifactId>
   <version>2.8.5</version>
</dependency>

You can get 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);  
System.out.println(json);

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 super classes) 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
  • Lets 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 {

	@SerializedName("src-switch")
	private String srcswitch;

	@SerializedName("src-port")
	private String srcport;
	@SerializedName("dst-switch")
	private String destswitch;
	@SerializedName("dst-port")
	private String destport;
	private String type;
...

	
	
	
Gson gson = new Gson();
LinksDetailsData = gson.fromJson(jsonString, LinksDetailsData.class);
Convert JSON with HTML content
  • Lets 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);
  • 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

{"brand":"Rover","doors":5}

// 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();
builder.excludeFieldsWithoutExposeAnnotation();
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);
GsonBuilder
Gson gson = new GsonBuilder()
     .registerTypeAdapter(Id.class, new IdTypeAdapter())
     .enableComplexMapKeySerialization()
     .serializeNulls()
     .setDateFormat(DateFormat.LONG)
     .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
     .setPrettyPrinting()
     .setVersion(1.0)
     .create();
Categories: JAVA

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.