我有Yaml,看起来像这样:
data_lists:
list1:(dynamic name)
- AA: true
BB: true
CC: "value"
- AA: false
BB: true
CC: "value2"
我想要得到的是将其存储到对象中
class BLA{
private boolean AA;
private boolean BB;
private String CC;
//getters and setters
}
我正在使用杰克逊库,但是我可以找到如何忽略根元素(如data_lsts和list1)并仅存储数组对象。
我当前的代码是:
ObjectMapper mapper = new ObjectMapper(YAML_FACTORY);
List<BLA> bla = Arrays.asList(mapper.readValue(ymlFile, BLA.class));
答案 0 :(得分:0)
给出示例,您可以使用TypeReference并将文件描述为Map<String, Map<String, List<BLA>>>
private static final String yamlString =
"data_lists:\n" +
" list1: \n" +
" - AA: true\n" +
" BB: true\n" +
" CC: \"value\"\n" +
" - AA: false\n" +
" BB: true\n" +
" CC: \"value2\"";
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
Map<String, Map<String, List<BLA>>> fileMap = mapper.readValue(
yamlString,
new TypeReference<Map<String, Map<String, List<BLA>>>>(){});
Map<String, List<BLA>> dataLists = fileMap.get("data_lists");
List<BLA> blas = dataLists.get("list1");
System.out.println(blas);
}
class BLA {
@JsonProperty("AA")
private boolean aa;
@JsonProperty("BB")
private boolean bb;
@JsonProperty("CC")
private String cc;
@Override
public String toString() {
return aa + "|" + bb + "|" + cc;
}
// Getters/Setters
}
此输出
[true|true|value, false|true|value2]
如果您有这样的列表列表:
data_lists:
list1:
- AA: true
BB: true
CC: "value"
- AA: false
BB: true
CC: "value2"
list2:
- AA: true
BB: true
CC: "value3"
- AA: false
BB: true
CC: "value4"
您可以获取"data_lists"
值作为集合
Map<String, List<BLA>> dataLists = fileMap.get("data_lists");
Collection<List<BLA>> blas = dataLists.values();
System.out.println(blas);
输出:
[[true|true|value, false|true|value2], [true|true|value3, false|true|value4]]