javaparsingyamlcommentsobjectmapper

ObjectMapper - YAML parse - ignore comments


YAML file example

---
# Author : John Doe
# Updated Date: 6/21/2024 4:23:22 PM
# Status: Deployed.
name: "stack overflow"
version: 5

While parsing the yaml file, How to ignore the comment lines that are starting with #

ObjectMapper mapper = new ObjectMapper(); 
MyDoc myDoc = mapper.readValue(response.toString(), MyDoc.class);

Solution

  • package nl.swilvan;
    
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
    
    import java.io.File;
    import java.io.IOException;
    
    public class Main {
        public static void main(String[] args) throws IOException {
    
            ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
            var ex = mapper.reader().forType(Example.class).readValue(new File("src/main/resources/example.yml"));
    
            System.out.println(mapper.writer().writeValueAsString(ex));
        }
    
        public static class Example {
    
            String name;
    
            public int getVersion() {
                return version;
            }
    
            public void setVersion(int version) {
                this.version = version;
            }
    
            int version;
    
    
            public String getName() {
                return name;
            }
    
            public void setName(String name) {
                this.name = name;
            }
        }
    }
    

    seems to work for me, i added https://mvnrepository.com/artifact/com.fasterxml.jackson.dataformat/jackson-dataformat-yaml/2.17.1 as a dependency. example.yml is your example yml