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
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。