Madeirey
Madeirey

Reputation: 172

Java - Parse JSON Array of Strings into String Array

[
    {
        "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++;
    }

Upvotes: 1

Views: 6322

Answers (2)

Madeirey
Madeirey

Reputation: 172

So I ended up getting it to work with these changes! I had never worked with JSON before this project and apparently I had it written wrong for what I was trying to do.

        JSONParser jsonParser2 = new JSONParser();
        try (FileReader reader = new FileReader("Locations.json")) {
            Object obj = jsonParser2.parse(reader);

            JSONArray locationsList = (JSONArray) obj;

            //Iterate over locations array
            locationsList.forEach(emp -> parseJSONLocations((JSONObject) emp, locations, objects));

        } catch (FileNotFoundException e) {
            System.out.println(e);
        } catch (IOException | ParseException e) {
            System.out.println(e);
        }

and then the method to add it all to a class was changed as such:

    private static void parseJSONLocations(JSONObject locations, Locations[] location, Objects[] object) {
        JSONObject locationObject = (JSONObject) locations.get("locations");
        String desc = (String) locationObject.get("description");
        String name = (String) locationObject.get("name");
        JSONArray objects = (JSONArray) locationObject.get("objects");

        Iterator<String> it = objects.iterator();
        List<Objects> objs = new ArrayList<>();
        while (it.hasNext()) {
            String mStr = it.next();
            for (Objects elm : object) {
                if (elm.getName().equals(mStr)) {
                    objs.add(elm);
                }
            }
        }

        JSONArray directions = (JSONArray) locationObject.get("directions");
        Map<String, String> map = new HashMap<>();
        Iterator<JSONObject> it2 = directions.iterator();
        while (it2.hasNext()) {
            JSONObject value = it2.next();
            map.put((String) value.get("direction"), (String) value.get("location"));
        }
        location[index2] = new Locations(desc, name, objs, map);
        index2++;
    }

But then I also had to change my JSON code, per jgolebiewski's suggestion:

[
    {
        "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": [{
                    "direction": "right",
                    "location": "empty room1"
                }, {
                    "direction": "left",
                    "location": "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": [{
                    "direction": "up",
                    "location": "hallway2"
                }, {
                    "direction": "down",
                    "location": "hallway1"
                }, {
                    "direction": "right",
                    "location": "start"
                }]
        }
    }
]

Thank you for this tutorial for helping as well: https://howtodoinjava.com/library/json-simple-read-write-json-examples/

Upvotes: 1

jgolebiewski
jgolebiewski

Reputation: 31

I am not sure what library you're using for json mapping, but i can give you some advices, which may help:

  • when mapping objects property try to map it to List<String> instead of String[]
  • changing directions property may help to map it to Map object:

try to change this: "directions": [{"right":"empty room1"}, {"left":"dungeon"}]

to this: "directions": {"right":"empty room1", "left":"dungeon"}

Upvotes: 1

Related Questions