snakeyaml dump пустое поле вместо нуля - PullRequest
0 голосов
/ 04 июля 2018

У меня есть LinkedHashMap, где некоторые значения могут быть нулевыми, и я хочу, чтобы они были сброшены как пустые поля вместо нулевых. Это вообще возможно или я нервы ломаю напрасно? Также, как я могу избавиться от одинарных кавычек, если напечатано целое число?

Мой код:

Map<String, Object> map = org.createOrgYamlMap();
    DumperOptions options= new DumperOptions();
    options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
    options.setPrettyFlow(true);
    Yaml yaml = new Yaml(options);
    PrintWriter writer = new PrintWriter(new File(orgDirectory.toString() + "/organization.yml"));
    yaml.dump(map, writer);

Дает мне файл yaml:

uuid: '123'
name: test1
document_vault: null

Что я хочу:

uuid: 123
name: test1
document_vault:

1 Ответ

0 голосов
/ 06 июля 2018

Переопределить метод представления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: ''
...