Search code examples
javaserializationyamlsnakeyaml

Creating a ruby optimized version while dumping in snakeyaml


I recently tried to dump an object to an .yaml file and everything works fine. But, the problem is I want an ruby optimized version since the output file is used by ruby. Currently, the dumped file contains the following:

{foo: null, bar: null, foo1: null, bar1: null}

But, I need the output as follows:

--- 
bar: ~
bar1: ~
foo: ~
foo1: ~

So, how can I do that using snakeyaml. I got the utf-8 optimized version of ruby at http://www.yamllint.com/.


Solution

  • If I understand your question then you might use yaml.dumpAsMap(map) instead of yaml.dump(map), and a TreeMap and then String.replace(String, String) like

    Map<String, String> map = new TreeMap<>();
    map.put("foo", null);
    map.put("bar", null);
    map.put("foo1", null);
    map.put("bar1", null);
    
    Yaml yaml = new Yaml();
    String output = yaml.dumpAsMap(map); // yaml.dump(map);
    System.out.println("---");
    System.out.println(output.replace("null", "~"));
    

    Output is (as requested)

    ------
    bar: ~
    bar1: ~
    foo: ~
    foo1: ~