[英]Gson: Modeling a Class for JSON with variable Intern Object
Goog Day to all: This is my first question and i may have failed to find a similar question, and so im posting this one. 所有人的Goog Day:这是我的第一个问题,我可能没有找到类似的问题,所以我张贴了这个问题。 I am making an app in android for Guild Wars 2 and I'm new, this is my first project for full implementng an app having all considerations for good practices. 我正在为《激战2》在android中制作一个应用,这是我的新手,这是我第一个全面实现具有良好实践考虑的应用的项目。 As for my problem I am now, modeling the clases for JSON strings responses from GW2 API. 关于我的问题,现在,我对来自GW2 API的JSON字符串响应的分类进行建模。 Lets Start with "item" API JSON: WIKI: https://wiki.guildwars2.com/wiki/API:2/items EXAMPLE: https://api.guildwars2.com/v2/items/28445 让我们以“ item” API JSON开头:WIKI: https ://wiki.guildwars2.com/wiki/API:2/ items示例: https : //api.guildwars2.com/v2/items/28445
I am modeling the class for GSON deserialization on A CLASS Diagram (not coded yet) and i'm having issues with the "details" object inside the "item" JSON. 我在CLASS CLASS(尚未编码)上为GSON反序列化建模该类,并且在“ item” JSON中的“ details”对象存在问题。 The "details" object is variable and may or may not have subobjects. “详细信息”对象是可变的,可能有也可能没有子对象。
So the issues Are: 因此,问题是:
Q1.1: the former is often a "more comfortable option" (although not as clean as the latter) as long as the various data types are simple enough. Q1.1:只要各种数据类型足够简单,前者通常是“更舒适的选择”(尽管不如后者)。 Unfortunately, this doesn't seem to be the case. 不幸的是,事实并非如此。 So I would personally go with the latter. 所以我个人会选择后者。
Q1.2: you would have to implement your own deserializer class. Q1.2:您将必须实现自己的反序列化器类。 A TL;DR version on how to do this can be found eg here or here . 有关如何执行此操作的TL; DR版本可以在此处或此处找到。 In your deserializer you would check for attribute "type" and check whether it's "LongBow", "Armor" or whatever, and return a respective class instance. 在反序列化器中,您将检查属性“ type”,并检查其是否是“ LongBow”,“ Armor”或其他,然后返回各自的类实例。
If you're interested in more detail, you can try here or you can just google something along the lines of "JsonSerializer" or "gson polymorphic array" etc. 如果您对更多细节感兴趣,可以在这里尝试,也可以按照“ JsonSerializer”或“ gson多态数组”等类似的方式对Google进行搜索。
Q2.1: If I understand corretly, Infix upgrade subobject and Infusion slots subobject are not dependent on the particular type of item (or particular subclass for our matters), so it is not necessary to make them as inner classes or anything. Q2.1:如果我正确理解,那么Infix升级子对象和Infusion插槽子对象并不依赖于特定的项目类型(或就我们而言而言特定的子类),因此没有必要将它们设置为内部类或任何其他类。 I'd make classes InfixUpgrade
and InfusionSlot
and add those as class members where they're relevant. 我将创建InfixUpgrade
和InfusionSlot
类,并将它们添加为相关的类成员。
Example: 例:
public class LongBow {
@SerializedName("infix_upgrade")
private InfixUpgrade infixUpgrade;
@SerializedName("infusion_slots")
private ArrayList<InfusionSlot> infusionSlots;
}
I hope this helped a bit. 我希望这能有所帮助。 Feel free to ask additional questions. 随时提出其他问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.