gson 反序列化到多态子类

gson 反序列化到多态子类

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

public class AnimalDeserializer implements JsonDeserializer<Animal> {

    @Override
    public Animal deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        JsonObject jsonObject = json.getAsJsonObject();
        String type = jsonObject.get("type").getAsstring();

        if ("dog".equals(type)) {
            return context.deserialize(jsonObject, Dog.class);
        } else if ("cat".equals(type)) {
            return context.deserialize(jsonObject, Cat.class);
        }

        throw new JsonParseException("UnkNown type: " + type);
    }
}

public class Main {
    public static void main(String[] args) {
        GsonBuilder gsonBuilder = new GsonBuilder();
        gsonBuilder.registerTypeAdapter(Animal.class, new AnimalDeserializer());
        Gson gson = gsonBuilder.create();

        String json = "{\"type\":\"dog\",\"name\":\"Buddy\",\"breed\":\"Labrador\"}";
        Animal animal = gson.fromJson(json, Animal.class);

        System.out.println(animal.getClass()); // 输出:class Dog
    }
}

相关文章

买水果
比较全面的redis工具类
gson 反序列化到多态子类
java 版本的 mb_strwidth
JAVA 反转字符串的最快方法,大概比StringBuffer.reverse()性...
com.google.gson.internal.bind.ArrayTypeAdapter的实例源码...