简体   繁体   中英

Parsing multiple json objects in java

I have this json file that I'm trying to parse in my program.

{
  "items": [{
        "0": {
          "item_name":"Test Item",
          "item_rarity":2,
          "item_material":"STICK",
          "required_level":1,
          "min_damage":100.0,
          "max_damage":200.0,
          "item_set":"The cool kids",
          "attributes":[{"name":"lifesteal","modifier":20}]
        },
          "1": {
            "item_name":"Test Item",
            "item_rarity":2,
            "item_material":"STICK",
            "required_level":1,
            "min_damage":100.0,
            "max_damage":200.0,
            "item_set":"The cool kids",
            "attributes":[{"name":"lifesteal","modifier":20}]
        }
  }]
}

I am printing the JSON string, but instead of getting the individual objects (0, then 1, then 2, etc...) it only gets the whole array every time I print it out.

Object obj = jsonParser.parse(new FileReader(new File(ValaCraft.getInstance().getDataFolder() + "/test.json")));
            JSONObject jsonObject = (JSONObject) obj;

            JSONArray items = (JSONArray) jsonObject.get("items");
            for (int i = 0; i < items.size(); i++) {
                JSONObject item = (JSONObject) items.get(i);
                System.out.print(item.toString());
            }

Anybody have an idea on how to parse this file (without GSON, attributes is a custom class and I found it complicated to use the auto parse that gson comes with).

What did you find troubling with GSON?

If you pass it to the gson.fromJSON as a JSONObject class, it should work, and you'll be able to get data from the JSON object.

  Gson gson = new Gson();
  JsonObject jsonFile = gson.fromJson(file.json, JsonObject.class);

Then you can call

JsonArray array = jsonFile.get("items").getAsJsonArray();

Then to grab the attributes from the first element of the array.

 array.get(0).getAsJsonObject().get("attributes").getAsJsonArray();

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