How does Java LibGDX parse JSON?

How does Java LibGDX parse JSON? … here is a solution to the problem.

How does Java LibGDX parse JSON?

I have a json file that contains the following:

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

How do I parse into an array of weapons? I’ve got the contents of this file as a string. Then I use libgdx JsonReader:

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

I also have a weapons class :

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

How do you put all the weapons into an array next?

Solution

There is no automatic mapping of parsed JSON to Java objects in libGDX, so you have to traverse the JSON yourself and create the appropriate objects. For an example of 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);
}

Related Problems and Solutions