gpt4 book ai didi

Java - 将 JSON 字符串数组解析为字符串数组

转载 作者:行者123 更新时间:2023-12-02 09:16:13 24 4
gpt4 key购买 nike

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

上面是我正在使用 Java 制作的基于文本的游戏的 JSON 文件片段。我能够彻底解析另一个文件,该文件在每个位置(对象和方向)都没有另一个数组,但是这个文件确实有一个数组,我陷入了困境。我需要将对象添加到字符串数组中,并将方向放入 map 中。下面是我用来解析它并将其添加到类对象数组中的代码!我知道我尝试将它们添加到字符串数组中的方式是完全错误的,但我将其保留,因此希望它能更好地理解我想要做什么。感谢您提前提供的任何帮助!

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++;
}

最佳答案

我不确定您使用哪个库进行 json 映射,但我可以给您一些建议,这可能会有所帮助:

  • 映射时 objects属性尝试将其映射到 List<String>而不是String[]
  • 改变directions属性可能有助于将其映射到 Map 对象:

尝试更改此设置:"directions": [{"right":"empty room1"}, {"left":"dungeon"}]

对此:"directions": {"right":"empty room1", "left":"dungeon"}

关于Java - 将 JSON 字符串数组解析为字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58961493/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com