Gson TypeAdapter 动态给JSON 增加、删除、转换 key-value

255 阅读1分钟

应用场景

一个类中包含一些没有直接对应字段的方法(例如只有getter方法)。如果想将这些getter方法的结果序列化为JSON中的key-value对,你可以通过注解或者自定义TypeAdapter来实现。

@SerializedName("customKey") 允许自定义属性名称对应的JSON key

@Expose 实际上用于控制哪些字段应该被序列化,默认不暴露字段

实体类中使用@JsonIgnoreProperties(value = { "property1", "property2" })将会在序列化和反序列化时忽略property1property2这两个属性。 @JsonIgnoreProperties(value = "tmcname")

自定义TypeAdapter

TypeAdapter 示例1:

import com.google.gson.*;
import java.lang.reflect.Type;

public class MyTypeAdapter implements JsonSerializer<MyDtoClass>, JsonDeserializer<MyDtoClass> {

    @Override
    public JsonElement serialize(MyClass src, Type typeOfSrc, JsonSerializationContext context) {
        JsonObject jsonObject = new JsonObject();

        jsonObject.add("myKey", new JsonPrimitive(src.getMethod()));

        // 如果有其他要添加的键值对,可以继续调用add方法

        return jsonObject;
    }

    @Override
    public MyClass deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        //throw new UnsupportedOperationException("This adapter only supports serialization.");
    }
}

    // 然后在GsonBuilder中注册这个TypeAdapter
    Gson gson = new GsonBuilder()
            .registerTypeAdapter(MyDtoClass.class, new MyTypeAdapter())
            .create();

TypeAdapter 示例2:

public class JsonGetterMethodTypeAdapter implements JsonSerializer<PVo> {


    @Override
    public JsonElement serialize(PVo src, Type typeOfSrc, JsonSerializationContext context) {

        JsonObject jsonObject = GsonUtil.getGson().toJsonTree(src).getAsJsonObject();
        jsonObject.addProperty("k","v");
        jsonObject.add("key", new JsonPrimitive(src.getFee()));
        // 如果有其他要添加的键值对,可以继续调用add方法
        return jsonObject;
    }
}

TypeAdapter 示例3:


import com.google.gson.*;
import java.lang.reflect.Method;

public class GsonExample {

    public static class MyClass {
        // 这是一个没有对应属性的get方法
        public String getValue() {
            return "some value";
        }
    }

    public static class MyClassAdapter extends TypeAdapter<MyClass> {
        @Override
        public void write(JsonWriter out, MyClass value) throws IOException {
            out.beginObject();
            // 调用get方法并将其作为JSON key
            out.name("value").value(value.getValue());
            out.endObject();
        }

        @Override
        public MyClass read(JsonReader in) throws IOException {
            // 实现反序列化逻辑(如果需要)
            return null;
        }
    }

    public static void main(String[] args) {
        GsonBuilder builder = new GsonBuilder();
        builder.registerTypeAdapter(MyClass.class, new MyClassAdapter());
        Gson gson = builder.create();

        MyClass myClass = new MyClass();
        String json = gson.toJson(myClass);
        System.out.println(json); // 将输出: {"value":"some value"}
    }
}