Untitled

 avatar
unknown
plain_text
a year ago
1.6 kB
7
Indexable
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class Yaml2Json {

    public static void main(String[] args) throws IOException {
        if (args.length != 1) {
            System.out.println("Usage: Yaml2Json <yaml_file>");
            System.exit(1);
        }

        File yamlFile = new File(args[0]);
        if (!yamlFile.exists()) {
            System.out.println("YAML file not found: " + yamlFile.getAbsolutePath());
            System.exit(1);
        }

        // Read the YAML content from the file
        String yamlContent = readFileContent(yamlFile);

        // Convert YAML to JSON using the provided method
        String json = convertYamlToJson(yamlContent);

        // Print the JSON output to the console
        System.out.println(json);
    }

    // Method to read the contents of a file
    private static String readFileContent(File file) throws IOException {
        try (FileInputStream fis = new FileInputStream(file)) {
            byte[] bytes = fis.readAllBytes();
            return new String(bytes);
        }
    }

    // Provided method for YAML to JSON conversion
    public static 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);
    }
}
Editor is loading...
Leave a Comment