简体   繁体   中英

Converting a list of POJO's to a YAML file in JAVA

I have found many examples in StackOverflow but I guess none of them are facing this problem which I have:

I am trying to convert a List of POJOs to a YAML format and writing the file onto the disk. I am using Snake Yaml with this dependancy in my Pom:

 <dependency>
   <groupId>org.yaml</groupId>
   <artifactId>snakeyaml</artifactId>
   <version>1.18</version>
  </dependency>

My code :

Pojo po = new Pojo();
po.setProperty1("po1");
po.setProperty2("po2");
po.setProperty3("po3");

DumperOptions options = new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
options.setPrettyFlow(true);

Yaml yaml = new Yaml(options);
String s = yaml.dump(po);

Output :
- !! com.test.Pojo
  Property1:"po1"
  Property2:"po2"
  Property3:"po3"

Desired output:
- Property1:"po1"
  Property2:"po2"
  Property3:"po3"

When I use yaml.dump(myObject) it also prints the object name along with its properties. Is there a way I can get the desired output?

You can use a Representer .

Setting the class tag to Tag.MAP should hide the class name.

Representer representer = new Representer();
representer.addClassTag(Pojo.class, Tag.MAP);

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