Warning: Undefined array key "night" in /www/wwwroot/dhaomu.com/wp-content/themes/b2/header.php on line 18

Java技术gson反序列化到多态子类

Java技术gson 反序列化到多态子类!Java技术: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
    }
}
温馨提示:
1.本站大部分内容均收集于网络!若内容若侵犯到您的权益,请发送邮件至:duhaomu@163.com,我们将第一时间处理!
2.资源所需价格并非资源售卖价格,是收集、整理、编辑详情以及本站运营的适当补贴,并且本站不提供任何免费技术支持。
3.所有资源仅限于参考和学习,版权归原作者所有,更多请阅读网站声明

给TA赞赏
共{{data.count}}人
人已赞赏
编程技巧

使用composer安装和使用Endroid/QrCode来生成二维码

2022-6-4 9:00:00

编程技巧

织梦list列表页调用body内容的教程

2022-6-6 0:00:00

0 条回复 A文章作者 M管理员

Warning: Trying to access array offset on value of type null in /www/wwwroot/dhaomu.com/wp-content/themes/b2/functions.php on line 3914

Warning: Trying to access array offset on value of type null in /www/wwwroot/dhaomu.com/wp-content/themes/b2/functions.php on line 3914
----《》
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索