Search code examples
javasnakeyaml

How to parse map using snakeyaml


I have below YAML.

---
ingress:
  backendServiceName: serv-deploy
  cluster_issuer: letsencrypt-es
  ingressClassName: nginx-lo
  tls_acme: "true"
route:
  hosts:
    - id: abc
      host: abc.com
    - id: xyz
      host: xyz.com

using below code, IM parsing this YAML

public class TestYamlMap {

    public static void main(String[] args) throws FileNotFoundException {
        // TODO Auto-generated method stub

        InputStream inputStream = new FileInputStream(new File("C:\\Automation\\values.yaml"));

        Yaml yaml = new Yaml(new Constructor(Values1.class));

        Values1 data = yaml.load(inputStream);

        data.getRoute().getHosts().forEach(x -> System.out.println(x.getHost()));
        data.getRoute().getHosts().forEach(x -> System.out.println(x.getId()));

    }

}

Model classes are below

public class Route {

    // private List<Host> hosts = new ArrayList<>();

    private List<Host> hosts = new ArrayList<>();

    public List<Host> getHosts() {
        return hosts;
    }

    public void setHosts(List<Host> hosts) {
        this.hosts = hosts;
    }

}

public class Host {
    
      private String host;
      public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    private String id;
        public String getHost() {
            return host;
        }
        public void setHost(String host) {
            this.host = host;
        }
        }

everything is working fine. My query is whether id and host are mapped with each other ?

If yes, how can i Get the host value based on ID ? for example , for id, abc , can I get host value as abc.com ?

If not, how can I use map in such yaml file and read the value based on key?


Solution

  • If you would like to read the host based on the key, I would suggest using a Key-value map instead of a List.

    Your yaml file would look like:

    ---
    ingress:
      backendServiceName: serv-deploy
      cluster_issuer: letsencrypt-es
      ingressClassName: nginx-lo
      tls_acme: "true"
    route:
      hosts:
        abc: 
          host: abc.com
        xyz:
          host: xyz.com
    

    Then you could access the data (depending on the snakeyaml api), something like:

    var abc = data.getRoute().getHosts().get("abc");
    

    Otherwise, you could get your host by iterating the hosts lists and checking for a fit:

    private Host getHost(String id){
      for(Host host : hosts){
        if(host.getId().equals(id){
          return host;
        } 
      }
      return null;
    }