繁体   English   中英

如何在SnakeYaml中解析部分YAML文件

[英]How to parse part of a YAML file in SnakeYaml

我是YAML的新手并且解析了一个YAML配置文件,如下所示:

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

我必须解析以下Map结构

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

AuthConfigServiceConfig是我们系统中的自定义对象。

有人可以提供一些提示怎么做?

有一个名为Jackson的 Java包,它处理YAML (和JSON,CSV和XML)和Java对象之间的映射。 您将遇到的大多数示例都是针对JSON的,但YAML链接显示切换是直截了当的。 一切都通过ObjectMapper

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

然后可以使用它通过反射反序列化您的对象:

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

您可以设置类似这样的类(为了方便起见,我已将所有内容公开):

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 {
  ...
}

请注意JsonProperty 注释 ,它将Java字段重命名为YAML字段。 我发现这是在Java中处理JSON和YAML最方便的方法。 我还必须使用流API来实现大型对象。

因此,由于您在Auth和Service配置中具有相同的属性,因此我在一个类中对其进行了简化以向您显示。

YamlConfig类看起来像这样:

public class YamlConfig {

  private Map<String, ServiceConfig> applications;

  //... getter and setters here
}

而Parser逻辑是这样的:

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

我在这个要点中分享了完整的代码: https//gist.github.com/marceldiass/f1d0e25671d7f47b24271f15c1066ea3

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM