Google Gson:JsonSerializer 和 JsonDeserializer

x33g5p2x  于2021-12-25 转载在 Go  
字(1.1k)|赞(0)|评价(0)|浏览(717)

本文内容大多基于官方文档和网上前辈经验总结,经过个人实践加以整理积累,仅供参考。

Gson 使用 JsonSerializer 接管序列化过程,JsonDeserializer 接管反序列化过程

1 JsonSerializer

测试代码:

@Test
public void test() throws IOException {
    JsonSerializer<String> stringJsonSerializer = new JsonSerializer<String>() {
        @Override
        public JsonElement serialize(String arg0, Type arg1, JsonSerializationContext arg2) {
            return new JsonPrimitive(arg0 + "_ADD");
        }
    };
    Gson gson = new GsonBuilder()
        .registerTypeAdapter(String.class, stringJsonSerializer)
        .create();
    System.out.println(gson.toJson("JSON"));
}

运行结果:

2 JsonDeserializer

测试代码:

@Test
public void test() throws IOException {
    Gson gson = new GsonBuilder()
        .registerTypeAdapter(String.class, new JsonDeserializer<String>() {
            @Override
            public String deserialize(JsonElement json, Type type, JsonDeserializationContext context)
                throws JsonParseException {
                String value = json.getAsString();
                if (value.equals("KEY")) {
                    return "That's it!";
                }
                return "Forget it...";
            }
        }).create();
    System.out.println(gson.fromJson("XYZ", String.class));
    System.out.println(gson.fromJson("KEY", String.class));
    System.out.println(gson.fromJson("ANY", String.class));
}

运行结果:

相关文章