Home >Java >javaTutorial >How to Create a Custom JSON Deserializer for Gson?

How to Create a Custom JSON Deserializer for Gson?

Barbara Streisand
Barbara StreisandOriginal
2024-12-10 11:53:14455browse

How to Create a Custom JSON Deserializer for Gson?

Custom JSON Deserializer for Gson

When receiving JSON data with custom structures, Gson's default deserialization process may not suffice. In such cases, a custom deserializer is necessary.

Consider the following Java class representing a user:

public class User {
    int id;
    String name;
    Timestamp updateDate;
}

And a JSON structure representing a list of users:

[{"id":1,"name":"Jonas","update_date":"1300962900226"},
{"id":5,"name":"Test","date_date":"1304782298024"}]

To deserialize this JSON into User instances, a custom deserializer can be defined:

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import java.lang.reflect.Type;
import java.sql.Timestamp;

public class UserDeserializer implements JsonDeserializer<User> {
    @Override
    public User deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {
        long time = json.getAsJsonPrimitive().getAsLong();
        return new User(
            json.get("id").getAsInt(),
            json.get("name").getAsString(),
            new Timestamp(time));
    }
}

This deserializer parses the JSON into a User instance, taking into account the specified field names and custom timestamp parsing.

To apply this deserializer to the Gson instance, use the registerTypeAdapter method:

GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(User.class, new UserDeserializer());
Gson gson = gsonBuilder.create();

Now, the JSON can be deserialized into a list of User instances using the modified Gson instance.

The above is the detailed content of How to Create a Custom JSON Deserializer for Gson?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn