使用 Gson 从 JSON 初始化类的字段
我正在尝试使用 Gson 来初始化我的字段,但没有成功。
String complex = "{'menu': { 'id': 'file', 'value': 'File', 'popup': { 'task':
[ {'value': 'New', 'onclick': 'CreateNewDoc()'}, {'value': 'Open', 'onclick': 'OpenDoc()'}, {'value': 'Close', 'onclick': 'CloseDoc()'}]
}}}";
尝试使用以下方法执行此操作:
TasksHolder th = gson.fromJson(complex, TasksHolder.class);
TaskHolder 类:
public class TasksHolder {
List<Task> task;
public TasksHolder() {
task = new ArrayList<Task>();
}
}
请建议如何才能填充 TaskHolder
的 task
。
I'm trying to use Gson to initialize my fields, but no success.
String complex = "{'menu': { 'id': 'file', 'value': 'File', 'popup': { 'task':
[ {'value': 'New', 'onclick': 'CreateNewDoc()'}, {'value': 'Open', 'onclick': 'OpenDoc()'}, {'value': 'Close', 'onclick': 'CloseDoc()'}]
}}}";
Trying to do that with:
TasksHolder th = gson.fromJson(complex, TasksHolder.class);
TaskHolder class:
public class TasksHolder {
List<Task> task;
public TasksHolder() {
task = new ArrayList<Task>();
}
}
Please advice what can be done to make task
of TaskHolder
to be filled.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是通用类型擦除。 GSON 不知道要创建什么类型的对象,因为您的类仅包含一个列表(有关
Task
的类型信息丢失)。以下是如何在 GSON 中处理此问题:
但这对你没有帮助,因为你需要父对象,而不仅仅是列表。恐怕您必须编写您自己的自定义序列化和反序列化方法
The problem is Generic Type Erasure. GSON has no idea, what kinds of objects to create because your class contains only a List (type information regarding
Task
is lost).Here's how to deal with this problem in GSON:
But that won't help you, since you want the parent object, not just the list. I'm afraid you will have to write your own Custom Serialization and Deserialization methods
您的 JSON 未映射到您定义的类:它缺少几个级别(具有“菜单”属性的主级对象,然后是实际包含 TaskHolder 的菜单对象。因此,您应该定义 JSON 映射到的类结构(否则如何Gson 知道什么要映射到哪里吗?),或者预处理 JSON 以删除
其他答案提到的类型擦除不应该是这里的问题:您的“任务”属性被声明为 List,并且。这应该足以让 Gson 确定泛型类型。是的,字段声明确实保留泛型类型信息;因此,虽然根类型需要类型引用对象,但它们不需要。根属性下的属性。
Your JSON does not map to class you define: it is missing couple of levels (main-level object that has 'menu' property, then menu object that actually contains TaskHolder. So you should either define class structure that JSON maps to (how else would Gson know what to map where?), or pre-process JSON to remove stuff you don't need.
Type-erasure mentioned by the other answer should NOT be the problem here: your 'task' property is declared as List, and that should be enough for Gson to determine generic type. Yes, field declarations do retain generic type information; type erasure has more to do with runtime information available via Class. So while type reference objects are needed for root types, they are not needed for properties under root properties.