importcom.fasterxml.jackson.databind.JsonNode;importcom.fasterxml.jackson.databind.ObjectMapper;importcom.fasterxml.jackson.dataformat.yaml.YAMLFactory;publicclassYamlToJsonConverter{publicstaticvoidmain(String[]args){try{// Sample YAML stringStringyamlString="name: John Doe\nage: 30\ncity: New York";// Create ObjectMapper for YAMLObjectMapperyamlMapper=newObjectMapper(newYAMLFactory());// Read YAML and convert to JSONJsonNodejsonNode=yamlMapper.readTree(yamlString);// Create ObjectMapper for JSONObjectMapperjsonMapper=newObjectMapper();// Convert JSON to StringStringjsonString=jsonMapper.writeValueAsString(jsonNode);// Print the resultSystem.out.println("YAML to JSON Conversion:\n"+jsonString);}catch(Exceptione){e.printStackTrace();}}}
Explanation:
Dependencies: This code uses the Jackson library for handling JSON and YAML. Make sure to include the necessary dependencies in your project.
YAML to JSON Conversion: The code creates an instance of ObjectMapper with a YAMLFactory to read YAML. It then reads the YAML string and converts it into a JsonNode.
JSON String Output: Another ObjectMapper is created for handling JSON. The JsonNode obtained from the YAML is converted to a JSON string using writeValueAsString().
Print Result: The final JSON string is printed.
This code assumes you have the Jackson library in your classpath. You can add it using Maven or Gradle.
Sharing is caring!