How do you parse a YAML file containing tagged maps and return nested Java Map<String, Object> objects, where each Java Map contains all entries from the corresponding YAML map, plus an entry where the key is a the String “objectType” and the value is the (String) name of the tag?
In other words, I'd like to parse tagged YAML objects as if they were JSON objects with an entry for the type.
For example, how do you parse this:
!ControlGroup
name: myGroup
controls:
- !Button
name: button1
size: 10
- !Knob
name: knob1
maxValue: 11
size: 7
as if it were this?:
objectType: ControlGroup
name: myGroup
controls:
- objectType: Button
name: button1
size: 10
- objectType: Knob
name: knob1
maxValue: 11
size: 7
I'm already using SnakeYAML in the project I'm working on, so if a solution exists using SnakeYAML, that would be ideal.
CodePudding user response:
what worked was this,
!!ControlGroup
name: myGroup
controls:
- !!Button
name: button1
size: 10
- !!Knob
name: knob1
maxValue: 11
size: 7
Yaml yaml = new Yaml();
InputStream url = SnakeYml.class.getClassLoader().getResourceAsStream("sample.yaml");
Map<String, Object> obj = yaml.load(url);
System.out.println(obj);
public class ControlGroup {
String name;
public ControlGroup() {};
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
....
CodePudding user response:
Try this,
ControlGroup controlGroup = yaml.load(url);
controlGroup.setObjectType(ControlGroup.class.getName());
System.out.println(yaml.dumpAsMap(controlGroup));
public class ControlGroup {
String objectType = this.getClass().getTypeName();
String name;
public ControlGroup() {};
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getObjectType()
{
return this.getClass().getTypeName();
}
public void setObjectType(String className)
{
this.objectType = className;
}
}
MAP -->
name: myGroup
objectType: ControlGroup