Java SnakeYaml - prevents dumping of link names

I have the following method that I use to convert an object to a yaml (which I can, for example, print to the console)

 @Nonnull private String outputObject(@Nonnull final ObjectToPrint packageSchedule) { DumperOptions options = new DumperOptions(); options.setAllowReadOnlyProperties(true); options.setPrettyFlow(true); return new Yaml(new Constructor(), new JodaTimeRepresenter(), options).dump(ObjectToPrint); } 

Everything is fine, but for some object contained in the ObjectToPrint structure, I get something like a reference name, and not the actual contents of the object, for example.

 !!com.blah.blah.ObjectToPrint businessYears: - businessYearMonths: 12 ppiYear: &id001 { endDate: 30-06-2013, endYear: 2013, startDate: 01-07-2012, startYear: 2012 } ppiPeriod: ppiYear: *id001 endDate: 27-03-2014 startDate: 21-06-2013 units: 24.000 number: 1 

As you can see from the above example, I have a ppiYear object ppiYear (marked as $id001 ), and the same object is used in ppiPeriod , but only the link name is displayed there, and not the contents of the object. How to print the contents of an object every time I use this object in my structure, which I want to convert to yaml ( ObjectToPrint ). PS. It would be nice not to print the link name at all ( &id001 ), but that doesn't matter

+6
source share
1 answer

This is because you are referring to the same object in different places. To avoid this, you need to create copies of these objects. Yaml does not have a flag to disable this, because you can get into endless loops in case of circular references. However, you can customize Yaml source code to ignore duplicate links:

Look at the serialization line ~ 170 of the serializeNode method:

 ... if ( this.serializedNodes.contains(node) ) { this.emmitter.emit( new AliasEvent( ... ) ); } else { serializedNodes.add(node); // <== Replace with myHook(serializedNodes,node); ... void myHook(serializedNodes,node) { if ( node class != myClass(es) to avoid ) { serializedNodes.add(node); } 

if you find a way to prevent Yaml from putting nodes in the serializedNodes collection, your problem will be solved, however your program will be infinite in circular references.

The best solution is to add a hook, which allows you not to register only the class that you want to write simple.

+4
source

Source: https://habr.com/ru/post/951599/


All Articles