0

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).

1
  • What is GSON anyway? Commented Dec 20, 2015 at 5:07

1 Answer 1

1

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.