YAML to JSON Using Java

Jan 14, 2024

1 min read

Published in

Here is the Codes for converting YAML to JSON

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

public class YamlToJsonConverter {

    public static void main(String[] args) {
        try {
            // Sample YAML string
            String yamlString = "name: John Doe\nage: 30\ncity: New York";

            // Create ObjectMapper for YAML
            ObjectMapper yamlMapper = new ObjectMapper(new YAMLFactory());

            // Read YAML and convert to JSON
            JsonNode jsonNode = yamlMapper.readTree(yamlString);

            // Create ObjectMapper for JSON
            ObjectMapper jsonMapper = new ObjectMapper();

            // Convert JSON to String
            String jsonString = jsonMapper.writeValueAsString(jsonNode);

            // Print the result
            System.out.println("YAML to JSON Conversion:\n" + jsonString);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Explanation:

  1. Dependencies: This code uses the Jackson library for handling JSON and YAML. Make sure to include the necessary dependencies in your project.

  2. 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.

  3. JSON String Output: Another ObjectMapper is created for handling JSON. The JsonNode obtained from the YAML is converted to a JSON string using writeValueAsString().

  4. 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!