Master JSON Serialization in Java: A Deep Dive into Gson

This article walks through why developers should replace FastJson with Gson, explains Gson's core features, demonstrates basic and advanced serialization and deserialization—including handling arrays, collections, generic types, custom serializers, and annotations—while providing complete code examples and best‑practice tips.

Programmer DD
Programmer DD
Programmer DD
Master JSON Serialization in Java: A Deep Dive into Gson

Introduction

This weekend I read several posts warning about a critical FastJson bug that caused OOM errors, which made me reconsider using heavyweight third‑party libraries without thorough evaluation. I decided to study Gson, an open‑source library that also converts Java objects to JSON, and document the migration steps for future projects.

All code snippets referenced in this article are available in the repository: https://github.com/wrcj12138aaa/gson-actions Supported versions: JDK 8 gson 2.8.5 junit 5.5.1 Lombok 1.18.8

Gson Overview

According to the official wiki, Gson is a Java library that can convert Java objects into their JSON representation and vice‑versa.

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。

Gson provides a simple API ( fromJson / toJson) to perform conversion, producing compact, readable JSON and supporting complex objects and custom representations.

We usually refer to the conversion between objects and JSON strings as serialization and deserialization (Serialization/Deserialization). Converting an object to a JSON string is called serialization, and converting a JSON string to an object is called deserialization.

Basic Usage of Gson

All serialization and deserialization operations rely on the com.google.gson.Gson object, which offers a rich set of public APIs.

Gson core object
Gson core object

Gson objects can be created in two ways:

Directly with the new keyword: Gson gson = new Gson(); Via GsonBuilder for additional customization: Gson gson = new GsonBuilder().create(); Both creation methods behave the same for basic operations, but GsonBuilder allows extra configuration such as pretty‑printing and null‑value handling.

Java Serialization

Simple Object Serialization

public class ResultTest {
    @Test
    void test_serialization() {
        Gson gson = new Gson();
        Result result = new Result(200, "成功", null);
        String json = gson.toJson(result);
        System.out.println("json is " + json);

        Gson buildedGson = new GsonBuilder().setPrettyPrinting().serializeNulls().create();
        String buildedJson = buildedGson.toJson(result);
        System.out.println("buildedJson is " + buildedJson);
    }

    class Result {
        private int code;
        private String message;
        private Object data;

        public Result(int code, String message, Object data) {
            this.code = code;
            this.message = message;
            this.data = data;
        }
    }
}

Running the test shows that the default Gson instance omits null fields, while enabling serializeNulls includes them, and setPrettyPrinting produces a more readable JSON format.

JsonObject Generation

Besides converting custom classes, you can build a JsonObject and serialize it with toJson:

@Test
void test_jsonObject_serialization() {
  Gson gson = new Gson();
  JsonObject jsonObject = new JsonObject();
  jsonObject.addProperty("code", 400);
  jsonObject.addProperty("message", "参数错误");
  String toJson = gson.toJson(jsonObject);
  Assertions.assertEquals("{\"code\":400,\"message\":\"参数错误\"}", toJson); // true
}

When adding complex values, use add(String, JsonElement) to insert nested objects:

Gson gson = new Gson();
JsonObject jsonObject = new JsonObject();
JsonObject nestJsonObject = new JsonObject();
nestJsonObject.addProperty("username", "one");
nestJsonObject.addProperty("score", 99);
jsonObject.add("data", nestJsonObject);
String toJson2 = gson.toJson(jsonObject);
System.out.println(toJson2); // {"code":400,"message":"参数错误","data":{"username":"one","score":99}}

JSON Deserialization

Simple Object Deserialization

@Test
void test_deserialization() {
    String json = "{\"code\":400,\"message\":\"参数错误\"}";
    Result result = new Gson().fromJson(json, Result.class);
    Assertions.assertEquals(400, result.code); // true
    Assertions.assertEquals("参数错误", result.message); // true
}

Map Deserialization

Gson can also deserialize JSON into a Map. The resulting map is a LinkedTreeMap, which preserves insertion order and stores numeric values as Double and booleans as Boolean:

@Test
void test_map() {
    String jsonString = "{'employee.name':'one','employee.salary':10}";
    Gson gson = new Gson();
    Map map = gson.fromJson(jsonString, Map.class);
    assertEquals(2, map.size());
    assertEquals("one", map.get("employee.name"));
    assertEquals(Double.class, map.get("employee.salary").getClass());
}

Advanced Gson Usage

After mastering basic operations, we explore generic type handling, custom serializers, and custom deserializers.

Generic Object Deserialization

class Result<T> {
    private int code;
    private String message;
    private T data;

    public Result(int code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }
}

Using TypeToken we can deserialize a JSON string into Result<User>:

@Test
void test_generic_object() {
  String json = "{\"code\":200,\"message\":\"操作成功\",\"data\":{\"username\": \"one\",\"avater\": \"image.jpg\"}}";
  Type type = new TypeToken<Result<User>>(){}.getType();
  Result<User> result = new Gson().fromJson(json, type);
  Assertions.assertEquals(200, result.code);
  Assertions.assertEquals("one", result.data.getUsername());
  Assertions.assertEquals("image.jpg", result.data.getAvater());
}

Custom Serialization

class DateSerializer implements JsonSerializer<Date> {
    SimpleDateFormat dateTime = new SimpleDateFormat("yyyy-MM-dd");
    @Override
    public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(dateTime.format(src));
    }
}

Register the serializer with GsonBuilder:

Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new DateSerializer()).create();
@Test
void test_dateSerializer() {
  MyObject myObject = new MyObject(new Date(), "one");
  Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new DateSerializer()).create();
  String json = gson.toJson(myObject);
  String expectedJson = "{\"date\":\"2019-09-08\",\"name\":\"one\"}";
  Assertions.assertEquals(expectedJson, json); // true
}

Custom Deserialization

class ResultDeserializer implements JsonDeserializer<Result> {
    @Override
    public Result deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        JsonObject object = json.getAsJsonObject();
        Result<Object> result = new Result<>(object.getAsJsonPrimitive("CODE").getAsInt(),
                object.getAsJsonPrimitive("MESSAGE").getAsString(), null);
        return result;
    }
}

Register the deserializer:

@Test
void test_resultDeserializer() {
    String json = "{\"CODE\": 400,\"MESSAGE\": \"参数错误\"}";
    Gson gson = new GsonBuilder().registerTypeAdapter(Result.class, new ResultDeserializer()).create();
    Result result = gson.fromJson(json, Result.class);
    Assertions.assertEquals(400, result.code); // true
    Assertions.assertEquals("参数错误", result.message); // true
}

Conclusion

This article summarized Gson's core serialization and deserialization APIs, demonstrated handling of arrays, collections, generic types, and showed how to extend Gson with custom serializers, deserializers, and annotations to meet various JSON processing needs.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaserializationJSONannotationsGsonDeserializationGsonBuilder
Programmer DD
Written by

Programmer DD

A tinkering programmer and author of "Spring Cloud Microservices in Action"

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.