Java GsonBuilder Example

In the example, we write an object into JSON. We use GsonBuilder to create Gson.
Gson is a Java serialization/deserialization library to convert Java Objects into JSON and back. Gson was created by Google for internal use and later open-sourced.

Java Gson Maven dependency

This is a Maven dependency for Gson.
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.2</version>
</dependency>

Java GsonBuilder Example

GsonBuilder builds Gson with various configuration settings. GsonBuilder follows the builder pattern, and it is typically used by first invoking various configuration methods to set desired options, and finally calling create().
In the example, we write an object into JSON. We use GsonBuilder to create Gson.
package net.javaguides.gson;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.io.PrintStream;

class User {

    private final String firstName;
    private final String lastName;

    public User(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }
}

public class GsonBuilderExample {

    public static void main(String[] args) throws IOException {

        try (PrintStream prs = new PrintStream(System.out, true,
            "UTF8")) {

            Gson gson = new GsonBuilder()
                .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
                .create();

            User user = new User("Tony", "Stark");
            gson.toJson(user, prs);
        }
    }
}
Output:
{"FirstName":"Tony","LastName":"Stark"}

Reference


Comments