There is a package for Java called Jackson that handles the mapping between YAML (and JSON, and CSV, and XML) and Java objects. Most of the examples you'll come across are for JSON, but the YAML link shows that the switch is direct. Everything goes through ObjectMapper :
ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
This can then be used to deserialize the object through reflection:
ApplicationCatalog catalog = mapper.readValue(yamlSource, ApplicationCatalog.class);
You would create your classes something like this (I made everything public for the convenience of the 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 { ... }
Check out the JsonProperty annotation , which renames your Java field to a YAML field. I consider this the most convenient way to work with JSON and YAML in Java. I also had to use the streaming API for really large objects.
Alex taylor
source share