简体   繁体   English

Java LibGDX如何解析JSON?

[英]Java LibGDX How to parse an JSON?

I have a json file with content like this: 我有一个json文件,内容如下:

{
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. 我已经将此文件的内容作为String获取。 Then I use libgdx JsonReader: 然后我使用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? 接下来我应该怎么做才能将所有武器放入阵列?

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. 在libGDX中没有自动映射解析的Json到Java对象,因此您必须自己遍历Json并创建适当的对象。 For sample that's how you parse weapons : 对于你解析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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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