[英]Read yaml to object using jackson
I have Yaml which looks like this: 我有Yaml,看起来像这样:
data_lists:
list1:(dynamic name)
- AA: true
BB: true
CC: "value"
- AA: false
BB: true
CC: "value2"
What I am trying to get is to store it to the object 我想要得到的是将其存储到对象
class BLA{
private boolean AA;
private boolean BB;
private String CC;
//getters and setters
}
I am using jackson library but I can found how to ignore root elements like data_lsts and lists1 and store only array objects. 我正在使用杰克逊库,但可以找到如何忽略根元素(如data_lsts和list1)并仅存储数组对象。
My current code is: 我当前的代码是:
ObjectMapper mapper = new ObjectMapper(YAML_FACTORY);
List<BLA> bla = Arrays.asList(mapper.readValue(ymlFile, BLA.class));
Given your example you can use a TypeReference and describe your file as Map<String, Map<String, List<BLA>>>
给定您的示例,您可以使用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
}
This outputs 这个输出
[true|true|value, false|true|value2]
If you have a list of lists like this: 如果您有这样的列表列表:
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"
You can get "data_lists"
values as a Collection 您可以获取"data_lists"
值作为集合
Map<String, List<BLA>> dataLists = fileMap.get("data_lists");
Collection<List<BLA>> blas = dataLists.values();
System.out.println(blas);
Outputs: 输出:
[[true|true|value, false|true|value2], [true|true|value3, false|true|value4]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.