[
{
"locations": {
"description": "You look around the room and see you are in an empty room with 2 doors to the left and to the right. Knowing not how you got there, you decide to figure out how to escape and get back to your normal life.",
"name": "start",
"objects": [ "" ],
"directions": [{"right":"empty room1"}, {"left":"dungeon"}]
}
},
{
"locations": {
"description": "Inside this room it looks like some sort of dungeon with a cage in the middle and blood lining the wall and floor.",
"name": "dungeon",
"objects": [ "map", "torch" ],
"directions": [{"up":"hallway2"}, {"down":"hallway1"}, {"right":"start"}]
}
}
]
Above is a snippet of the JSON file I am working with for a text based game I am making in Java. I was able to parse thorough a different file that did not have another array in each location (the objects and directions), but this one does have an array and I am quite stuck. I need the objects to be added to an array of strings and the directions to be put into a Map. Below is the code I am using to parse though it and add it to an array of class objects! I know how I attempted to add them to an array of strings is quite wrong but I am leaving it so hopefully it is better understood what I was trying to do. Thank you for any help in advance!
JSONParser jsonParser2 = new JSONParser();
try (FileReader reader = new FileReader("Locations.json")) {
//Read JSON file
Object obj = jsonParser2.parse(reader);
JSONArray locationsList = (JSONArray) obj;
System.out.println(locationsList);
//Iterate over locations array
locationsList.forEach(emp -> parseJSONLocations((JSONObject) emp, locations));
} catch (FileNotFoundException e) {
System.out.println(e);
} catch (IOException | ParseException e) {
System.out.println(e);
}
private static void parseJSONLocations(JSONObject locations, Locations[] location) {
//Get locations object within list
JSONObject locationObject = (JSONObject) locations.get("locations");
//Get location description
String desc = (String) locationObject.get("description");
System.out.println(desc);
//Get location name
String name = (String) locationObject.get("name");
System.out.println(name);
//Get location objects
String[] objects = (String[]) locationObject.get("objects");
for (String o : objects) {
System.out.println(o);
}
//get location directions (direction : location)
Map<String, String> directions = (Map<String, String>) locationObject.get("directions");
for (String key : directions.keySet()) {
String value = directions.get(key);
System.out.println(key + " " + value);
}
//location[index] = new Locations(desc, name, objects, directions);
index++;
}
directions. Because a JSON array usually contains multiple JSON objects whose keys are identical but values are not.