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