我正試圖找到讀取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