简体   繁体   中英

Reading an Object that contains an Array of objects from JSON in Java

I am trying to read this JSON into Java:

{
  "custom enchants": {
    "Explosive Bow": {
      "max enchant level": " 1",
      "name": "Explosive",
      "enchant type": " explosive"
    },
    "Poison Bow": {
      "max enchant level": "4",
      "name": "Poison",
      "enchant type": "poison"
    }
  }

Which is generated by this code here:

     JSONObject explosiveBowObject = new JSONObject();
explosiveBowObject.put("name", "Explosive");
explosiveBowObject.put("enchant type", " explosive");
explosiveBowObject.put("max enchant level", " 1");

JSONObject poisonBowObject = new JSONObject();
poisonBowObject.put("name", "Poison");
poisonBowObject.put("enchant type", "poison");
poisonBowObject.put("max enchant level", "4");

generatedEnchants.put("Explosive Bow", explosiveBowObject);
generatedEnchants.put("Poison Bow", poisonBowObject);
jsonObject.add(generatedEnchants);

I am struggling with reading in the json object, which contains the jsonarray of jsonobjects. Any help is appreciated!

Thanks

Managed to Solve it by figuring out something along these lines:

ArrayList<Object> arrayList = new ArrayList<>();
        for(Object object1 : jsonObject){
            System.out.println("Json Object Value: " + object1);
            if(object1 instanceof JSONObject){
                System.out.println(((JSONObject) object1).keySet());
                for(Object object : ((JSONObject)object1).keySet()){
                    arrayList.add(object);
                }
            }
        }
        String name = "t";
        for (int i =0; i < arrayList.size(); i++){
            System.out.println("Array List " + i + " " + arrayList.get(i));
            if(arrayList.get(i) instanceof JSONObject){
                name = (String) ((JSONObject)arrayList.get(i)).get("name");
            }
        }

See original post for the rough idea of how to loop over a json array containing json objects.

Answer:

public void registerCustomEnchants() throws IOException, ParseException {
    JSONArray enchantJSONArray = (JSONArray)new JSONParser().parse(new FileReader(String.valueOf(pathToJSONFile)));
    for(Object o : enchantJSONArray){
        jsonArray.add(o);
    }
    Iterator iterator = jsonArray.iterator();
    while (iterator.hasNext()) {
        JSONObject jsonObject1 = ((JSONObject) iterator.next());
        Iterator<? extends Map.Entry<Object, Object> > it = jsonObject1.entrySet().iterator();
        while(it.hasNext()) {
            String name = null, enchantType = null;
            long maxEnchantLevel =0;
            Map.Entry<Object, Object> pair = it.next();
            if(pair.getKey().equals("name")){
                name = (String) pair.getValue();
            }
            if(pair.getKey().equals("enchant type")){
                enchantType = (String) pair.getValue();
            }
            if(pair.getKey().equals("max enchant level")){
                maxEnchantLevel = (long)pair.getValue();
            }
            parseEnchant(name, enchantType, maxEnchantLevel);
        }
    }
}

public void parseEnchant(String name, String enchantType, long maxEnchantLevel){
    new CustomEnchant(id++, name,enchantType, maxEnchantLevel);
}

/**
 * Creates a sample config with 2 usable items with custom enchants.
 * @throws IOException
 */
private void createDefaultCustomEnchantsJSONFile() throws IOException {
    FileReader fileReader = new FileReader(String.valueOf(pathToJSONFile));

    if (!checkIfDefaultExists()) {
        JSONObject explosiveBowObject = new JSONObject();
        explosiveBowObject.put("max enchant level", 1);
        explosiveBowObject.put("enchant type", "explosive");
        explosiveBowObject.put("name", "Explosive");

        JSONObject poisonBowObject = new JSONObject();
        poisonBowObject.put("max enchant level", 4);
        poisonBowObject.put("enchant type", "poison");
        poisonBowObject.put("name", "Poison");

        jsonArray.add(explosiveBowObject);
        jsonArray.add(poisonBowObject);

        //Enables the pretty version of Gson fortmatting
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        String json = gson.toJson(jsonArray);

        //Writes the shit to the file.
        FileWriter fileWriter = new FileWriter(String.valueOf(pathToJSONFile));
        fileWriter.write(json);
        fileWriter.flush();
    }
}

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