How do I convert from YAML to JSON in Java?

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')

Leave a Comment