我正试图找到读取Java中的YAML文件的最佳方法。我不确定哪个解析器是最好的解析器,但是目前我的解决方案是读取动态的(如果用户希望在文件中添加更多的内容,下次程序加载时)是一系列for循环,转换为从ArrayLists和hashmaps并解析原始字符串。Java YAML读取动态变化文件的最佳方法
例如:
HashMap<Object, Object> perWaveHashMap = (HashMap)waveConfiguration.getList("waves").get(wave); //wave-1
for(Object mobObject : perWaveHashMap.values()){
ArrayList<Object> mobObjectArrayList = (ArrayList) mobObject;
for(Object mob : mobObjectArrayList){
HashMap<Object, Object> mobHashMap = (HashMap)mob;
String mobNameString = null;
for(Object mobName : mobHashMap.keySet()){
mobNameString = mobName.toString();
}
for(Object mobAttribute : mobHashMap.values()){
HashMap<Object, Object> attributesToGive = (HashMap)mobAttribute;
final ArrayList<Object> attributeList = new ArrayList<>();
for(Object attribute : attributesToGive.values()){
attributeList.add(attribute);
}
assert mobNameString != null;
final String finalMobNameString = mobNameString;
System.out.println("Final Mob Name String: " + finalMobNameString);
if(finalMobNameString.equalsIgnoreCase("vintr")){
Mobs.isSpecialBossWave =true;
new Vintr();
} else {
if (attributeList.size() == 1) {
Mobs.addMobs((int) attributeList.get(0), EntityType.valueOf(finalMobNameString.toUpperCase()));
} else if (attributeList.size() == 2) {
Mobs.addMobs((int) attributeList.get(0), EntityType.valueOf(finalMobNameString.toUpperCase()), (int) attributeList.get(1));
} else if (attributeList.size() == 3) {
Mobs.addMobs((int) attributeList.get(0), EntityType.valueOf(finalMobNameString.toUpperCase()), (int) attributeList.get(1), (boolean) attributeList.get(2));
} else if (attributeList.size() == 4) {
Mobs.addMobs((int) attributeList.get(0), EntityType.valueOf(finalMobNameString.toUpperCase()), (int) attributeList.get(1), (boolean) attributeList.get(2), (boolean) attributeList.get(3));
} else if (attributeList.size() == 5) {
Mobs.addMobs((int) attributeList.get(0), EntityType.valueOf(finalMobNameString.toUpperCase()), (int) attributeList.get(1), (boolean) attributeList.get(2), (boolean) attributeList.get(3), (boolean) attributeList.get(4));
} else if (attributeList.size() == 6) {
Mobs.addMobs((int) attributeList.get(0), EntityType.valueOf(finalMobNameString.toUpperCase()), (int) attributeList.get(1), (boolean) attributeList.get(2), (boolean) attributeList.get(3), (boolean) attributeList.get(4), (boolean) attributeList.get(5));
}
}
}
}
}
基本上,YML文件看起来像这样:
waves:
- 1:
- zombie:
amount: 1
modifier: 2
boss: false
beeline: false
- 1:
- spider:
amount: 12
modifier: 2
boss: false
beeline: false
hunter: true
-2 :
- mobname:
-options
的方式我的代码是正确的,现在,让我来添加尽可能多的“波”,因为我想,以及我在每次浪潮中需要的暴民数量。我发现我做代码的方式真的很难且很难处理,并且正在寻找更好的方法来解决这个问题。
欢迎任何帮助!
感谢
不清楚的要求。首先,它是什么意思“动态”?那么,你是否想要一种解析YAML的方法? (答案:使用SnakeYAML)你需要将文本反序列化为域对象吗? (建议:使用YamlBeans) – Raffaele
每次启动程序时,我只会读取一次文件。动态的意义在于它可以被改变,并且在程序下次加载时它必须读取新的改变。 – Kato