How do I convert from YAML to JSON in Java? How do I convert from YAML to JSON in Java? json json

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


Thanks to HotLicks tip (in the question comments) I finally achieve the conversion using the libraries org.json and SnakeYAML in this way:

private static String convertToJson(String yamlString) {    Yaml yaml= new Yaml();    Map<String,Object> map= (Map<String, Object>) yaml.load(yamlString);    JSONObject jsonObject=new JSONObject(map);    return jsonObject.toString();}

I don't know if it's the best way to do it, but it works for me.


Big thanks to Miguel A. Carrasco he infact has solved the issue. But his version is restrictive. His code fails if root is list or primitive value. Most general solution is:

private static String convertToJson(String yamlString) {    Yaml yaml= new Yaml();    Object obj = yaml.load(yamlString);    return JSONValue.toJSONString(obj);}