java gson fromjson,Gson “fromJson” with 'T'

本文探讨如何在抽象类Storage中,通过继承并重写get方法,实现从JSON文件读取数据并转换为具体子类如GroupStorage。重点在于如何使用Gson将JSON解析为T类型,适用于实际项目中的数据获取与对象实例化。
摘要由CSDN通过智能技术生成

I have an class with "T extends StorageClass". You can extend this class and put another class instend of the "T" for example "GroupStorage extends Storage. In the "Storage" class is an method called "get". Now i want that method to convert json to the "T" class, in my case to the "Group" class. Maybe you will understand when you look to the code below.

public abstract class Storage {

// This should return whatever T is.

public T get(String groupName) {

T t = null;

File file = new File(this.groupFolderPath, groupName + ".json");

if (file.exists()) {

try {

FileReader reader = new FileReader(file);

// 'T.class' is not possible

t = Storage.GSON.fromJson(reader, T.class);

} catch (Exception e) {

e.printStackTrace();

Bukkit.getLogger().warning("Failed to read " + groupName + ".json!");

}

} else {

Bukkit.getLogger().warning("The group " + groupName + " does not exists!");

}

return t;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值