Serialise ObjectNode to Yaml

This method, serializeToYaml, converts a given Java object into a YAML-formatted string using the Jackson library. It applies specific serialization settings to ensure a clean and human-readable output.
 avatar
xy241
java
5 months ago
769 B
6
Indexable
public static String serializeToYaml(Object object) throws JsonProcessingException {
    if (object == null) {
        return null;
    }

    // Create YAML factory with standard settings
    YAMLFactory yamlFactory = new YAMLFactory()
            .enable(YAMLGenerator.Feature.MINIMIZE_QUOTES)
            .disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER);

    // Create and configure the ObjectMapper
    ObjectMapper objectMapper = new ObjectMapper(yamlFactory);
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

    // Perform the serialization
    return objectMapper.writeValueAsString(object);
}
Editor is loading...
Leave a Comment