简体   繁体   中英

Jackson/YAML: Parse key-value into class

I my input yaml file, I have the following:

services:
  postgresql:
    image: "postgres:10"
  redis:
    image: "redis:4"

It's easy to parse services field into a Map<String, Service> :

public class DockerCompose {
    public static class Service {
        private String image;
    }

    private Map<String, Service> services;
}

I would like to parse the services field in a List<Service> with the name in the field name in Service as following:

public class DockerCompose {
    public static class Service {
        private String name;
        private String image;
    }

    private List<Service> services;
}

Is this possible?

The easiest option is add custom setter for deserialization and getter for serialization.

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<>();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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