xiaozi 2023-12-29 17:49:33

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
    }
}

评论

首页 - Wiki
Copyright © 2011-2024 iteam. Current version is 2.138.0. UTC+08:00, 2024-12-22 11:06
浙ICP备14020137号-1 $访客地图$