Jackson / YAML:将键值分解为类

时间:2017-11-14 20:10:46

标签: java jackson yaml jackson2

我的输入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;
}

这可能吗?

1 个答案:

答案 0 :(得分:0)

最简单的选择是添加用于反序列化的自定义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<>();
}