java - Jackson 将 YAML 文件反序列化为 Map(没有自定义反序列化器)

标签 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 字段代表 map 键。

有没有办法在省略 SiteConfiguration 实例数组的同时执行相同的操作?是使用自定义反序列化器来做到这一点的唯一方法吗?

最佳答案

更改 YAML 的结构。如果要将数据反序列化为映射,则需要在 YAML 文件中将其作为映射启动。您的示例中有一系列映射,但您需要映射的映射。

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

Example 2.4. Sequence of Mappings (players’ statistics)

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

Example 10.1. !!map Examples

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,无需自定义反序列化器。

关于java - Jackson 将 YAML 文件反序列化为 Map(没有自定义反序列化器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52153301/

相关文章:

java - 如何将鼠标事件委托(delegate)给 JavaFX 中的所有底层重叠 Pane ?

java - 在 showconfirmDialog 中使用工具提示

c++ - 如何将 hash_map 与 char* 一起使用并进行字符串比较?

clojure 将lazy-seq转换为 HashMap

hashmap - 使用 Rust HashMap - .find() 没有返回匹配的预期值

java - 我想并排输出多个三角形,但它们都出现在彼此的顶部

java - 自动生成包含类字段的映射

javascript - Node JS |类型错误 : Cannot read property 'first_name' of undefined

asp.net - 从启用 AJAX 的 WCF 服务返回错误详细信息

java - 放心 : posting json request having both String and Integer