[英]Jackson/YAML: Parse key-value into class
我输入yaml文件,我有以下内容:
services:
postgresql:
image: "postgres:10"
redis:
image: "redis:4"
将services
字段解析为Map<String, Service>
很容易:
public class DockerCompose {
public static class Service {
private String image;
}
private Map<String, Service> services;
}
我想解析services
领域中List<Service>
在该域的名称name
的Service
如下:
public class DockerCompose {
public static class Service {
private String name;
private String image;
}
private List<Service> services;
}
这可能吗?
最简单的选项是添加用于反序列化的自定义setter和用于序列化的getter。
public static class DockerCompose {
public static class Service {
@JsonIgnore // for serialization
private String name;
private String image;
}
@JsonProperty("services") // for derserialization
public void setServicesMap(Map<String, Service> servicesMap){
for (Map.Entry<String, Service> entry :servicesMap.entrySet()) {
entry.getValue().name = entry.getKey();
services.add(entry.getValue());
}
}
@JsonProperty("services") // for serialization
public Map<String, Service> getServicesMap() {
Map<String, Service> map = new HashMap<>();
for(Service s: services)
map.put(s.getName(), s);
return map;
}
@JsonIgnore // for serialization
private List<Service> services = new ArrayList<>();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.