使用 jackson 读取 yaml 到对象

我有 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


}

我正在使用 jackson 库,但我可以找到如何忽略根元素(如 data_lsts 和 list1)并仅存储数组对象。


我目前的代码是:


ObjectMapper mapper = new ObjectMapper(YAML_FACTORY);

List<BLA> bla = Arrays.asList(mapper.readValue(ymlFile, BLA.class));


FFIVE
浏览 327回答 1
1回答

慕姐8265434

鉴于您的示例,您可以使用TypeReference并将您的文件描述为Map<String, Map<String, List<BLA>>>private static final String yamlString =&nbsp; &nbsp; "data_lists:\n" +&nbsp; &nbsp; "&nbsp; &nbsp; &nbsp; list1:&nbsp; \n" +&nbsp; &nbsp; "&nbsp; &nbsp; &nbsp; &nbsp; - AA: true\n" +&nbsp; &nbsp; "&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; BB: true\n" +&nbsp; &nbsp; "&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; CC: \"value\"\n" +&nbsp; &nbsp; "&nbsp; &nbsp; &nbsp; &nbsp; - AA: false\n" +&nbsp; &nbsp; "&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; BB: true\n" +&nbsp; &nbsp; "&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; CC: \"value2\"";public static void main(String[] args) throws Exception {&nbsp; &nbsp; ObjectMapper mapper = new ObjectMapper(new YAMLFactory());&nbsp; &nbsp; Map<String, Map<String, List<BLA>>> fileMap = mapper.readValue(&nbsp; &nbsp; &nbsp; &nbsp; yamlString,&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; new TypeReference<Map<String, Map<String, List<BLA>>>>(){});&nbsp; &nbsp; Map<String, List<BLA>> dataLists = fileMap.get("data_lists");&nbsp; &nbsp; List<BLA> blas = dataLists.get("list1");&nbsp; &nbsp; System.out.println(blas);}class BLA {&nbsp; &nbsp; @JsonProperty("AA")&nbsp; &nbsp; private boolean aa;&nbsp; &nbsp; @JsonProperty("BB")&nbsp; &nbsp; private boolean bb;&nbsp; &nbsp; @JsonProperty("CC")&nbsp; &nbsp; private String cc;&nbsp; &nbsp; @Override&nbsp; &nbsp; public String toString() {&nbsp; &nbsp; &nbsp; &nbsp; return aa + "|" + bb + "|" + cc;&nbsp; &nbsp; }&nbsp; &nbsp; // Getters/Setters}这输出[true|true|value, false|true|value2]如果您有这样的列表:data_lists:&nbsp; list1:&nbsp;&nbsp;&nbsp; &nbsp; - AA: true&nbsp; &nbsp; &nbsp; BB: true&nbsp; &nbsp; &nbsp; CC: "value"&nbsp; &nbsp; - AA: false&nbsp; &nbsp; &nbsp; BB: true&nbsp; &nbsp; &nbsp; CC: "value2"&nbsp; list2:&nbsp;&nbsp;&nbsp; &nbsp; - AA: true&nbsp; &nbsp; &nbsp; BB: true&nbsp; &nbsp; &nbsp; CC: "value3"&nbsp; &nbsp; - AA: false&nbsp; &nbsp; &nbsp; BB: true&nbsp; &nbsp; &nbsp; 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]]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java