简体   繁体   中英

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. 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. As for my problem I am now, modeling the clases for JSON strings responses from GW2 API. Lets Start with "item" API JSON: WIKI: https://wiki.guildwars2.com/wiki/API:2/items EXAMPLE: 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. The "details" object is variable and may or may not have subobjects.

So the issues Are:

  1. The "details" Subobject changes depending on the id requested. Q1.1: Should i create a BIG detail Class with all possibilities added and use Gson to leave empty those properties who won't match? or create one class for each different subobjects (in API subobject meaning Armor, Weapon, Trinket, etc).
    Q1.2: If I pick the later option how does GSON now what subObject/class to pick?.
  2. If the Subobject(2nd level) Has inner Object(3rd level) these smaller objects are only 2 kinds. Q2.1:should i make subclasses inside each subObject (second level) that has these objects(third level) inside?

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. 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. A TL;DR version on how to do this can be found eg here or here . In your deserializer you would check for attribute "type" and check whether it's "LongBow", "Armor" or whatever, and return a respective class instance.

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.

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. I'd make classes InfixUpgrade and InfusionSlot and add those as class members where they're relevant.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM