GSON获取嵌套对象

时间:2018-08-19 15:44:29

标签: java android json gson

我正在和一些Gson挣扎,却找不到我要找的答案。希望我不会创建重复项。

基本上,我有一个武器类别,其中有一个子弹类。但是,并非所有武器都有弹药,即手榴弹。

我的武器类别如下:

public class Weapon_gson implements Serializable {

private ArrayList<String> Attachments, BuyFrom, Footer;
private String Description, MainImage, Name, Icon, Notes;

private Ammunition Ammunition;
private GeneralData GeneralData;
private Looting Looting;
private Performance Performance;

public Weapon_gson(ArrayList<String> attachments, ArrayList<String> buyFrom, ArrayList<String> footer, String description, String mainImage, String name, String icon, String notes, Weapon_gson.Ammunition ammunition, Weapon_gson.GeneralData generalData, Weapon_gson.Looting looting, Weapon_gson.Performance performance) {
    Attachments = attachments;
    BuyFrom = buyFrom;
    Footer = footer;
    Description = description;
    MainImage = mainImage;
    Name = name;
    Icon = icon;
    Notes = notes;

    Ammunition = ammunition;
    GeneralData = generalData;
    Looting = looting;
    Performance = performance;
}

private class Ammunition {
    ArrayList<String> AcceptedAmmunition;
    String Caliber, DefaultAmmo, DefaultMag, MuzzleVelocity;

}

public String getCaliber() {
    return Ammunition.Caliber;
}

}

然后我用Gson加载数据

    Gson gson = new GsonBuilder().create();
    Type collectionType = new TypeToken<Collection<Weapon_gson>>(){}.getType();

    ArrayList<Weapon_gson> TempWeaponArray = new ArrayList<>();

    // Read file in stream mode
    try (JsonReader reader = new JsonReader(in)) {
        reader.beginArray();
        while (reader.hasNext()) {
            // Read data into object model
            Weapon_gson weapon = gson.fromJson(reader, Weapon_gson.class);
            TempWeaponArray.add(weapon);
        }
    }
    return TempWeaponArray;

这将正确返回武器对象,并且如果json数据包含Ammunition.Caliber,我将能够获得口径。但是,如果json不包含弹药,则弹药将为null,并且无法调用机芯。

尝试从空对象引用中读取字段'java.lang.String uk.co.design2dev.escapefromtarkov.Weapons.Weapon_gson $ Ammunition.Caliber'

在调试器中查看显示弹药为空,所以我明白了为什么它无法获得口径,但是我不确定如何最好地解决这个问题?

稍后,当我使用适配器填充recyclerview时,我想隐藏口径textview(如果它不可用),但我不确定如何最好地实现这一点。

    if(currentWeapon.getCaliber() == null){
        holder.weapon_calibler_tv.setVisibility(View.GONE);
    }else{
        holder.weapon_calibler_tv.setVisibility(View.VISIBLE);
        holder.weapon_calibler_tv.setText(currentWeapon.getCaliber());
    }

如果以这种方式与Gson一起工作,我什至需要构造函数吗? 任何建议将不胜感激。

预先感谢

0 个答案:

没有答案