Java LibGDX How to parse an JSON?

萝らか妹 提交于 2019-12-21 06:23:03

问题


I have a json file with content like this:

{
players: [
    {
        name: "",
        hp: 100
    },
    {
        name: "",
        hp: 120
    }
],
weapons: [
    {
        name: "Desert Eagle",
        price: 100
    },
    {
        name: "AK-47",
        price: 150
    }
]
}

How to parse it into an array of weapons? I already get content of this file as String. Then I use libgdx JsonReader:

JsonValue json = new JsonReader().parse(text);

Also I have a class for Weapons:

class Weapon {
    private String name;
    private int price;
}

What should I do next to put all the weapons into an array?


回答1:


There is no automatic mapping of parsed Json to Java object in libGDX, so you have to traverse Json and create appropriate objects by yourself. For sample that's how you parse weapons:

JsonValue json = new JsonReader().parse(text);
Array<Weapon> weapons = new Array<Weapon>();
JsonValue weaponsJson = json.get("weapons");
for (JsonValue weaponJson : weaponsJson.iterator()) // iterator() returns a list of children
{
    Weapon newWeapon = new Weapon();
    newWeapon.name = weaponJson.getString("name");
    newWeapon.price = weaponJson.getInt("price");
    weapons.add(newWeapon);
}


来源:https://stackoverflow.com/questions/28266823/java-libgdx-how-to-parse-an-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!