Fixed the value of empty YAML nodes being written as "null". Thanks rcjrrjcr!

By: EvilSeph <evilseph@unaligned.org>
This commit is contained in:
Bukkit/Spigot 2011-06-07 18:14:32 -04:00
parent b91a8f0389
commit 46b2baddf6

View File

@ -10,7 +10,15 @@ import java.util.Map;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.introspector.Property;
import org.yaml.snakeyaml.nodes.CollectionNode;
import org.yaml.snakeyaml.nodes.MappingNode;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.NodeTuple;
import org.yaml.snakeyaml.nodes.SequenceNode;
import org.yaml.snakeyaml.nodes.Tag;
import org.yaml.snakeyaml.reader.UnicodeReader;
import org.yaml.snakeyaml.representer.Represent;
import org.yaml.snakeyaml.representer.Representer;
/**
@ -44,7 +52,6 @@ import org.yaml.snakeyaml.representer.Representer;
* <p>This class is currently incomplete. It is not yet possible to get a node.
* </p>
*
* @author sk89q
*/
public class Configuration extends ConfigurationNode {
private Yaml yaml;
@ -58,7 +65,7 @@ public class Configuration extends ConfigurationNode {
options.setIndent(4);
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
yaml = new Yaml(new SafeConstructor(), new Representer(), options);
yaml = new Yaml(new SafeConstructor(), new EmptyNullRepresenter(), options);
this.file = file;
}
@ -136,3 +143,41 @@ public class Configuration extends ConfigurationNode {
return new ConfigurationNode(new HashMap<String, Object>());
}
}
class EmptyNullRepresenter extends Representer {
public EmptyNullRepresenter() {
super();
this.nullRepresenter = new EmptyRepresentNull();
}
protected class EmptyRepresentNull implements Represent {
public Node representData(Object data) {
return representScalar(Tag.NULL, ""); // Changed "null" to "" so as to avoid writing nulls
}
}
// Code borrowed from snakeyaml (http://code.google.com/p/snakeyaml/source/browse/src/test/java/org/yaml/snakeyaml/issues/issue60/SkipBeanTest.java)
@Override
protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, Object propertyValue, Tag customTag) {
NodeTuple tuple = super.representJavaBeanProperty(javaBean, property, propertyValue, customTag);
Node valueNode = tuple.getValueNode();
if (valueNode instanceof CollectionNode) {
// Removed null check
if (Tag.SEQ.equals(valueNode.getTag())) {
SequenceNode seq = (SequenceNode) valueNode;
if (seq.getValue().isEmpty()) {
return null; // skip empty lists
}
}
if (Tag.MAP.equals(valueNode.getTag())) {
MappingNode seq = (MappingNode) valueNode;
if (seq.getValue().isEmpty()) {
return null; // skip empty maps
}
}
}
return tuple;
}
// End of borrowed code
}