将YAML文件杰克逊反序列化为Map(没有自定义反序列化器)

时间:2018-09-03 16:14:41

标签: java json hashmap jackson yaml

我正在尝试将YAML文件加载到Map的实例中。有没有一种方法可以在不定义自定义反序列化器的情况下加载它(例如使用注释?)?

这是我的YAML文件的示例:

- site: First Site
  url: some_url
  username: some_name
  password: some_password
- site: Second Site
  url: its_url
  username: its_name
  password: its_password

这是Java bean类,用于将一个“站点配置”反序列化为(由http://www.jsonschema2pojo.org/生成):

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import org.apache.commons.lang3.builder.ToStringBuilder;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
        "site",
        "url",
        "username",
        "password"
})
public class SiteConfiguration {

    @JsonProperty("site")
    private String site;
    @JsonProperty("url")
    private String url;
    @JsonProperty("username")
    private String username;
    @JsonProperty("password")
    private String password;

    /**
     * No args constructor for use in serialization
     *
     */
    public SiteConfiguration() {
    }

    /**
     *
     * @param site
     * @param username
     * @param password
     * @param url
     */
    public SiteConfiguration(String site, String url, String username, String password) {
        super();
        this.site = site;
        this.url = url;
        this.username = username;
        this.password = password;
    }

    @JsonProperty("site")
    public String getSite() {
        return site;
    }

    @JsonProperty("site")
    public void setSite(String site) {
        this.site = site;
    }

    @JsonProperty("url")
    public String getUrl() {
        return url;
    }

    @JsonProperty("url")
    public void setUrl(String url) {
        this.url = url;
    }

    @JsonProperty("username")
    public String getUsername() {
        return username;
    }

    @JsonProperty("username")
    public void setUsername(String username) {
        this.username = username;
    }

    @JsonProperty("password")
    public String getPassword() {
        return password;
    }

    @JsonProperty("password")
    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this).append("site", site).append("url", url).append("username", username).append("password", password).toString();
    }

}

最后,这是将上面的YAML反序列化为Map的代码。

    private static Map<String,SiteConfiguration> sites;
    public static SiteConfiguration getSiteConfiguration(String key) {
        if (sites == null) {
            ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
            try {
//          todo this finishes on: com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.LinkedHashMap` out of START_ARRAY token
//                sites = mapper.readValue(YamlReader.class.getClass().getResource("/site-configuration.yaml"), new TypeReference<Map<String,SiteConfiguration>>() {});
                SiteConfiguration[] sitesArray = mapper.readValue(YamlReader.class.getClass().getResource("/site-configuration.yaml"), SiteConfiguration[].class);
                sites = new HashMap<>();
                for (SiteConfiguration site : sitesArray) {  //todo is there Jackson built-in deserialization?
                    sites.put(site.getSite(), site);
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return sites.get(key);
    }

如您所见,我分两个步骤进行操作。首先,我将文件反序列化为SiteConfiguration个实例的数组,然后将它们放入Map中,其中site字段表示映射键。

是否有一种方法可以省略SiteConfiguration实例数组?使用自定义解串器是唯一的方法吗?

1 个答案:

答案 0 :(得分:0)

更改YAML的结构。如果要将数据反序列化为地图,则需要以YAML文件中的地图开始。您的示例中有一系列映射,但是您想要一个映射映射。

https://yaml.org/spec/1.2/spec.html#id2759963

  

示例2.4。映射顺序   (玩家的统计信息)

-
  name: Mark McGwire
  hr:   65
  avg:  0.278
-
  name: Sammy Sosa
  hr:   63
  avg:  0.288
     

示例10.1。 !!地图示例

Block style: !!map
  Clark : Evans
  Ingy  : döt Net
  Oren  : Ben-Kiki

尝试以下方法:

First Site:
  site: First Site
  url: some_url
  username: some_name
  password: some_password
Second Site:
  site: Second Site
  url: its_url
  username: its_name
  password: its_password

此结构适用于没有自定义反序列化器的Jackson 2.9.9。