We will cover how to use Gson to convert JSON into Java Object and Java Object into JSON in the following points
- Use Gson – Maven/Gradle
- Object to JSON
- JSON to Object
- 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
You can get the latest version of Maven here.
Convert Object to JSON
Convert JSON to Object
- 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.
- 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.
Add Custom variables naming
- Let’s say our Json is something like this.
- 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.
Convert JSON with HTML content
- Let’s take this Java Object as example
If we convert this into JSON String
- 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
Print JSON in Readable format
Excluding Fields from JSON
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.
- 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:
- 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.