Search code examples
javapolymorphismsnakeyaml

SnakeYAML polymorphy


I want to parse Docker-compose.yml with SnakeYAML (or some other parser). The issue I run into is with attributes that can either be a String or a more complex object, like configs, which support a "short" syntax and a "long" syntax:

short

version: "3.3"
services:
  redis:
    image: redis:latest
    deploy:
      replicas: 1
    configs:
      - my_config
      - my_other_config
configs:
  my_config:
    file: ./my_config.txt
  my_other_config:
    external: true

long

version: "3.3"
services:
  redis:
    image: redis:latest
    deploy:
      replicas: 1
    configs:
      - source: my_config
        target: /redis_config
        uid: '103'
        gid: '103'
        mode: 0440
configs:
  my_config:
    file: ./my_config.txt
  my_other_config:
    external: true

How can I map this to SnakeYAML? Currently I have created Java Beans to model the different elements, and model configs as List<String> but that obviously only works for the short syntax.


Solution

  • If SnakeYaml encounters a String where it expects to deserialize an object, it looks for a constructor with a String argument.

    So in the example, it is enough to define a JavaBean for the long syntax of config, and then add a constructor to that which takes the short syntax as argument.