How do I convert from YAML to JSON in Java?

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);
}

I found the example did not produce correct values when converting Swagger (OpenAPI) YAML to JSON. I wrote the following routine:

  private static Object _convertToJson(Object o) throws JSONException {
    if (o instanceof Map) {
      Map<Object, Object> map = (Map<Object, Object>) o;

      JSONObject result = new JSONObject();

      for (Map.Entry<Object, Object> stringObjectEntry : map.entrySet()) {
        String key = stringObjectEntry.getKey().toString();

        result.put(key, _convertToJson(stringObjectEntry.getValue()));
      }

      return result;
    } else if (o instanceof ArrayList) {
      ArrayList arrayList = (ArrayList) o;
      JSONArray result = new JSONArray();

      for (Object arrayObject : arrayList) {
        result.put(_convertToJson(arrayObject));
      }

      return result;
    } else if (o instanceof String) {
      return o;
    } else if (o instanceof Boolean) {
      return o;
    } else {
      log.error("Unsupported class [{0}]", o.getClass().getName());
      return o;
    }
  }

Then I could use SnakeYAML to load and output the JSON with the following:

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

JSONObject jsonObject = (JSONObject) _convertToJson(map);
System.out.println(jsonObject.toString(2));

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

Tags:

Java

Json

Yaml