简体   繁体   中英

Map a subtree of YAML to POJO using Jackson

I am using Jackson's Object mapper to map a YAML to my Pojo. My YAML is a configuration file and I want to read config of only a particular type using Jackson.

Following is how my YAML looks like:

A:
  a:
    1: i
    2: ii
    3: iii

  b:
   foo: bar

I want to read all the data lying under Aa ie 1,2,3 in a POJO.

My POJO looks like

public class MyPojo{
 String one;
 String two;
 String three;
}

You get the idea. I want to map all the children of a particular node in Pojo.

I know I can readTree("myYaml").get("A").get("a") and get list of all children. But is there any way already in Jackson to convert that subtree to Pojo just like readValue(file, class) ??

No one helped me so I helped my self:).

There is a method treeToValue(TreeNode, Class) , so nesting treeToValue and readTree helps in doing the desired thing.

So in order to read the subtree Aa , we need to do

File myYamlFile = new File(someclass.getClass().getClassLoader().getResource("myYAML").getFile())
MyPojo myPojo = jacksonObjectMapper.treeToValue(jacksonObjectMapper.readTree(myYamlFile).get("A").get("a"), MyPojo.class)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM