AnxiousGuy
AnxiousGuy

Reputation: 45

While converting java object into yaml file, its also adding the object name

I am dumping java object to a file in yaml format using snakeYaml. Its dumping the data correctly, but while doing that, it is also appending the full object name in the file. Here is the code I am using to dump object to the file:

PrintWriter writer = new PrintWriter(new File(fileName));
Yaml yaml = new Yaml();
yaml.dump(testObject, writer);

testObject is an object of custom Java class. Output file contains:

!!org.test.common.TestReportObject
fail: 0
succ: 1
total: 1
tests:
- className: org.test.common.TAPTest
  methods:
  - {fail: false, methodName: test1, stackTrace: null, success: true}

Is there a way, so that the output file does not contains

!!org.test.common.TestReportObject

line?

P.S.: Its the very first line of the output file. I am unable to add comments.

Upvotes: 2

Views: 1725

Answers (1)

Saurabhcdt
Saurabhcdt

Reputation: 1158

Class name (with package) is the tag used by snakeyaml for the document. It's default tag is MAP & is not printed. SO setting TAG for your class to MAP will not print it in yml output file. - This also impacts how you read the yml. Here's complete solution:

Maven dependency:

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

Java Code:

PrintWriter writer = new PrintWriter(new File("pathTo/output.yml"));
        DumperOptions options = new DumperOptions();
        options.setIndent(2);
        options.setPrettyFlow(true);
        options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
                    
        Representer representer = new Representer();
        representer.addClassTag(TestReportObject.class, Tag.MAP);
                    
        Yaml yaml = new Yaml(representer, options);
        yaml.dump(testObject, writer);

here, Representer helps to set the tag for your class as MAP-which is default tag & hence snakeyaml doesnt prints it. So the output will be without class name as first line.

In addition to first line, it will not add class name for other subclasses in your TestReportObject class e.g. TAPTest

Upvotes: 3

Related Questions