How to parse part of a YAML file in SnakeYaml

Niranjan picture Niranjan · Feb 5, 2016 · Viewed 11k times · Source

I am new to YAML and have parse a YAML config file that looks like:

applications:
  authentication:
    service-version: 2.0
    service-url: https://myapp.corp/auth
    app-env: DEV
    timeout-in-ms: 5000
    enable-log: true

  service1:
    enable-log: true
    auth-required: true
    app-env: DEV
    timeout-in-ms: 5000
    service-url: https://myapp.corp/service1
    service-name: SomeService1
    service-version: 1.1
    service-namespace: http://myapp.corp/ns/service1

  service2:
    enable-log: true
    auth-required: true
    app-env: DEV
    timeout-in-ms: 5000
    service-url: https://myapp.corp/service2
    service-name: SomeService2
    service-version: 2.0
    service-namespace: http://myapp.corp/ns/service2

I have to parse to following Map structure

+==================================+
| Key              |               |
+==================================+
| authentication   | AuthConfig    |
+----------------------------------+
| service1         | ServiceConfig |
+----------------------------------+
| service2         | ServiceConfig |
+----------------------------------+

AuthConfig and ServiceConfig are the custom objects in our system.

Can someone provide some hints how to do it?

Answer

Alex Taylor picture Alex Taylor · Feb 6, 2016

There is a package for Java called Jackson that handles mapping between YAML (and JSON, and CSV, and XML) and Java objects. Most examples you will come across are for JSON, but the YAML link shows that switching is straight-forward. Everything goes through an ObjectMapper:

ObjectMapper mapper = new ObjectMapper(new YAMLFactory());

That can then be used to deserialize your object via reflection:

ApplicationCatalog catalog = mapper.readValue(yamlSource, ApplicationCatalog.class);

You would set up your classes something like this (I've made everything public for ease of example):

class ApplicationCatalog {
  public AuthConfig authentication;
  public ServiceConfig service1;
  public ServiceConfig service2;
}

class AuthConfig {
  @JsonProperty("service-version")
  public String serviceVersion;
  @JsonProperty("service-url")
  public String serviceUrl;
  @JsonProperty("app-env")
  public String appEnv;
  @JsonProperty("timeout-in-ms")
  public int timeoutInMs;
  @JsonProperty("enable-log")
  public boolean enableLog;
}

class ServiceConfig {
  ...
}

Notice the JsonProperty annotation which is renaming your Java field to YAML field. I find this the most convenient way of dealing with JSON and YAML in Java. I've also had to use the streaming API for really large objects.