我是 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 |
+----------------------------------+
AuthConfig
and ServiceConfig
是我们系统中的自定义对象。
有人可以提供一些如何做的提示吗?
Java 有一个包叫Jackson https://github.com/FasterXML/jackson处理之间的映射YAML https://github.com/FasterXML/jackson-dataformat-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注解 https://github.com/FasterXML/jackson-annotations这会将您的 Java 字段重命名为 YAML 字段。我发现这是在 Java 中处理 JSON 和 YAML 的最方便的方法。我也不得不使用流媒体API http://wiki.fasterxml.com/JacksonInFiveMinutes#Streaming_API_Example对于非常大的物体。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)