Skip to content

How do I convert from YAML to JSON in Java?

I just want to convert a string that contains a yaml into another string that contains the corrseponding converted json using Java.

For example supose that I have the content of this yaml

---
paper:
   uuid: 8a8cbf60-e067-11e3-8b68-0800200c9a66
   name: On formally undecidable propositions of Principia Mathematica and related systems I.
   author: Kurt Gödel.
tags:
   - tag:
       uuid: 98fb0d90-e067-11e3-8b68-0800200c9a66
       name: Mathematics
   - tag:
       uuid: 3f25f680-e068-11e3-8b68-0800200c9a66
       name: Logic

in a String called yamlDoc:

String yamlDoc = "---npaper:n   uuid: 8a... etc...";

I want some method that can convert the yaml String into another String with the corresponding json, i.e. the following code

String yamlDoc = "---npaper:n   uuid: 8a... etc...";
String json = convertToJson(yamlDoc); // I want this method
System.out.println(json);

should print:

{
    "paper": {
        "uuid": "8a8cbf60-e067-11e3-8b68-0800200c9a66",
        "name": "On formally undecidable propositions of Principia Mathematica and related systems I.",
        "author": "Kurt Gödel."
    },
    "tags": [
        {
            "tag": {
                "uuid": "98fb0d90-e067-11e3-8b68-0800200c9a66",
                "name": "Mathematics"
            }
        },
        {
            "tag": {
                "uuid": "3f25f680-e068-11e3-8b68-0800200c9a66",
                "name": "Logic"
            }
        }
    ]
}

I want to know if exists something similar to the convertToJson() method in this example.

I tried to achieve this using SnakeYAML, so this code

 Yaml yaml = new Yaml();
 Map<String,Object> map = (Map<String, Object>) yaml.load(yamlDoc);

constructs a map that contain the parsed YAML structure (using nested Maps). Then if there is a parser that can convert a map into a json String it will solve my problem, but I didn’t find something like that neither.

Any response will be greatly appreciated.

Answer

Here is an implementation that uses Jackson:

String convertYamlToJson(String yaml) {
    ObjectMapper yamlReader = new ObjectMapper(new YAMLFactory());
    Object obj = yamlReader.readValue(yaml, Object.class);

    ObjectMapper jsonWriter = new ObjectMapper();
    return jsonWriter.writeValueAsString(obj);
}

Requires:

compile('com.fasterxml.jackson.dataformat:jackson-dataformat-yaml:2.7.4')