Search code examples
javaarraysstringsnakeyaml

Parse string array using snakeYaml


I have a yaml file in this way

A: ["aa","bb","cc"]

I wonder is there any YAML library can parse this string array rather than using string library?


Solution

  • You can use snakeyaml like this:

    define library in your pom.xml:

    <dependency>
        <groupId>org.yaml</groupId>
        <artifactId>snakeyaml</artifactId>
        <version>1.23</version>
    </dependency>
    

    Mapper class:

    public class YamlEntity {
        private Map<String, List<String>> value;
    
        public Map<String, List<String>> getValue() {
            return value;
        }
    
        public void setValue(Map<String, List<String>> value) {
            this.value = value;
        }
    
        @Override
        public String toString() {
            return "YamlEntity [value=" + value + "]";
        }
    
     }
    

    yaml file like example.yaml

    value: [aa, bb, cc]
    

    and your method:

    public static void readYaml() {
        Yaml yaml = new Yaml();
        InputStream is = App.class.getResourceAsStream("example.yaml");
    
        Map<String, List<YamlEntity>> ye = yaml.load(is);
        System.out.println(ye.get("value"));
    }
    

    result is: [aa, bb, cc]