How to parse part of a YAML file in SnakeYaml

与世无争的帅哥 提交于 2019-12-04 03:23:22
Alex Taylor

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.

So as you have the same properties in the Auth and Service configuration I simplified that in one class to show you here.

The YamlConfig class look like this:

public class YamlConfig {

  private Map<String, ServiceConfig> applications;

  //... getter and setters here
}

And the the Parser logic is something like that :

Yaml yaml = new Yaml(new Constructor(YamlConfig.class));
InputStream input = new FileInputStream(new File("/tmp/apps.yml"));
YamlConfig data = yaml.loadAs( input, YamlConfig.class);

I shared the full code in this gist: https://gist.github.com/marceldiass/f1d0e25671d7f47b24271f15c1066ea3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!