我正在尝试创建一个插件,其中我存储了一些我的艺术项目的数据和一些属性。
这是我的YAML文件的内容:
rates:
- 391:
mul: 10000
store: 5000
- 392:
mul: 9000
store: 5000所以这基本上是一张地图列表(至少我认为是这样)。这是我的JAVA代码,我试图访问‘391’的键'mul‘:
List<Map<?,?>> rates;
rates= getConfig().getMapList("rates");
for(Map<?,?> mp : rates){
Map <?,?> test = (Map<?,?>) mp.get("" + item);
player.sendMessage(test.toString());// HERE I get null pointer exception, and the following lines if this line wasn't there in the first place
player.sendMessage("Mul is: " + test.get("mul"));
player.sendMessage("Store is: " + test.get("store"));
}根据建议的答案,这是我的测试代码,在这里我仍然可以得到NullPointerException:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Map;
import net.sourceforge.yamlbeans.YamlException;
import net.sourceforge.yamlbeans.YamlReader;
public class Test {
public static void main(String[] args) throws FileNotFoundException, YamlException{
YamlReader reader = new YamlReader(new FileReader("config.yml"));
Map map = (Map) reader.read();
Map itemMap = (Map) map.get("391");
System.out.println(itemMap.get("mul"));//This is where I get the exception now
System.out.println(itemMap.get("store"));
}
}发布于 2016-12-21 16:52:25
手工解析yaml可能很繁琐,而且容易出错。使用像yamlbeans这样的库可能更容易。
http://yamlbeans.sourceforge.net/
package com.jbirdvegas.q41267676;
import com.esotericsoftware.yamlbeans.YamlReader;
import java.io.StringReader;
import java.util.List;
import java.util.Map;
public class YamlExample {
public static void main(String[] args) throws Exception {
String yamlInput =
"rates:\n" +
"- 391:\n" +
" mul: 10000\n" +
" store: 5000\n" +
"- 392:\n" +
" mul: 9000\n" +
" store: 5000";
YamlReader reader = new YamlReader(new StringReader(yamlInput));
Map map = (Map) reader.read();
// rates is a list
List<Map> rates = (List<Map>) map.get("rates");
// each item in the list is a map
for (Map itemMap : rates) {
// each map contains a single map the key is [ 391|392 ]
itemMap.forEach((key, value) -> {
System.out.println("Key: " + key);
// the value in in this map is itself a map
Map embededMap = (Map) value;
// this map contains the values you want
System.out.println(embededMap.get("mul"));
System.out.println(embededMap.get("store"));
});
}
}
}这些指纹:
Key: 391
10000
5000
Key: 392
9000
5000这是一个简单的用法,但是yamlbeans还提供了类似反射类模型的GSON,如果这更适合您的需要的话。
发布于 2016-12-21 20:59:22
你认为YAML是地图列表的假设是错误的。顶层是一个具有单键值对的映射,其键是rates,值是一个包含两个元素的序列。
这些元素中的每一个都是用一个键值对进行映射,其中键是一个数字(391,392),其值是一个有两个键值对的映射。
左边有一个破折号(-)并不意味着在顶层有一个序列( YAML文件中没有列表,即用您的编程语言构造)。如果序列是特定键的值,则这些序列元素可以与键处于相同的缩进级别,就像在YAML文件中一样。
https://stackoverflow.com/questions/41267676
复制相似问题