0

I'm currently creating a Cluedo game and I'm editing the playerpiece class, I have also created a json file called data.json to store data about the playerpiece, for instance: Character (e.g Colonel Mustard), Weapon etc.

{
  "PlayerPieces": {
    "0": "Col Mustard",
    "1": "Prof Plum",
    "2": "Rev Green",
    "3": "Mrs Peacock",
    "4": "Miss Scarlett",
    "5": "Mrs White"
  },
  "Weapons": {
    "0": "Dagger",
    "1": "Candlestick" ,
    "2": "Revolver",
    "3": "Rope",
    "4": "Lead Piping",
    "5": "Spanner"
  }
}

At the moment, I'm trying to figure out how I can create an arraylist of all possible instances of the PlayerPieces, any help on how to get started would be greatly, greatly appreciated!

1 Answers1

0

Something like this will help I hope.

String stringToParse = "{\r\n"
                + "  \"PlayerPieces\": {\r\n"
                + "    \"0\": \"Col Mustard\",\r\n"
                + "    \"1\": \"Prof Plum\",\r\n"
                + "    \"2\": \"Rev Green\",\r\n"
                + "    \"3\": \"Mrs Peacock\",\r\n"
                + "    \"4\": \"Miss Scarlett\",\r\n"
                + "    \"5\": \"Mrs White\"\r\n"
                + "  },\r\n"
                + "  \"Weapons\": {\r\n"
                + "    \"0\": \"Dagger\",\r\n"
                + "    \"1\": \"Candlestick\" ,\r\n"
                + "    \"2\": \"Revolver\",\r\n"
                + "    \"3\": \"Rope\",\r\n"
                + "    \"4\": \"Lead Piping\",\r\n"
                + "    \"5\": \"Spanner\"\r\n"
                + "  }\r\n"
                + "}";

        try {
            Map<String, String> attributes = new HashMap<>();
            JSONObject obj = new JSONObject(stringToParse);
            if (obj.has("PlayerPieces")) {
                JSONObject objPlayerPieces = obj.getJSONObject("PlayerPieces");
                Iterator<String> keysCat = objPlayerPieces.keys();
                while (keysCat.hasNext()) {
                    String key = keysCat.next();
                    attributes.put(key, objPlayerPieces.getString(key));
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

Therefore, you will get all the attributes of "PlayerPieces" inside the attributes hashmap for as long as you have them defined in the json file.

Kidus Tekeste
  • 651
  • 2
  • 10
  • 28