Переопределить метод представленияMapping класса Представителя.
Map<String, Object> map = org.createOrgYamlMap();
Representer representer = new Representer() {
@Override
protected Node representMapping(Tag tag, Map<?, ?> mapping, Boolean flowStyle) {
List<NodeTuple> value = new ArrayList<NodeTuple>(mapping.size());
MappingNode node = new MappingNode(tag, value, flowStyle);
representedObjects.put(objectToRepresent, node);
boolean bestStyle = true;
for (Map.Entry<?, ?> entry : mapping.entrySet()) {
Node nodeKey = representData(entry.getKey());
//If value is null then treat it as empty string.
Node nodeValue = entry.getValue() == null ?
representData("") : representData(entry.getValue());
if (!(nodeKey instanceof ScalarNode && ((ScalarNode) nodeKey).getStyle() == null)) {
bestStyle = false;
}
if (!(nodeValue instanceof ScalarNode && ((ScalarNode) nodeValue).getStyle() == null)) {
bestStyle = false;
}
value.add(new NodeTuple(nodeKey, nodeValue));
}
if (flowStyle == null) {
if (defaultFlowStyle != FlowStyle.AUTO) {
node.setFlowStyle(defaultFlowStyle.getStyleBoolean());
} else {
node.setFlowStyle(bestStyle);
}
}
return node;
}
};
DumperOptions options= new DumperOptions();
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
options.setPrettyFlow(true);
Yaml yaml = new Yaml(representer, options);
PrintWriter writer = new PrintWriter(new File(orgDirectory.toString() + "/organization.yml"));
yaml.dump(map, writer);
Код теста:
public static void main(String[] args) throws FileNotFoundException {
Map<String, Object> lhm = new LinkedHashMap<>();
lhm.put("c", null);
DumperOptions options = new DumperOptions();
Representer representer = new Representer() {
@Override
protected Node representMapping(Tag tag, Map<?, ?> mapping, Boolean flowStyle) {
List<NodeTuple> value = new ArrayList<NodeTuple>(mapping.size());
MappingNode node = new MappingNode(tag, value, flowStyle);
representedObjects.put(objectToRepresent, node);
boolean bestStyle = true;
for (Map.Entry<?, ?> entry : mapping.entrySet()) {
Node nodeKey = representData(entry.getKey());
Node nodeValue = entry.getValue() == null ?
representData("") : representData(entry.getValue());
if (!(nodeKey instanceof ScalarNode && ((ScalarNode) nodeKey).getStyle() == null)) {
bestStyle = false;
}
if (!(nodeValue instanceof ScalarNode && ((ScalarNode) nodeValue).getStyle() == null)) {
bestStyle = false;
}
value.add(new NodeTuple(nodeKey, nodeValue));
}
if (flowStyle == null) {
if (defaultFlowStyle != FlowStyle.AUTO) {
node.setFlowStyle(defaultFlowStyle.getStyleBoolean());
} else {
node.setFlowStyle(bestStyle);
}
}
return node;
}
};
options.setDefaultFlowStyle(FlowStyle.BLOCK);
Yaml yaml = new Yaml(representer, options);
String s = yaml.dump(lhm);
System.out.println(s);
}
Выход:
c: ''