简体   繁体   中英

How to create Map from yaml file with Jackson?

This is the class:

public class YamlMap {

    Map<String, String> mp = new HashMap<>();

    String get(String key) {
        return this.mp.get(key);
    }
}

and this is the props.yml:

mp:
  key1: ok
  key2: no

When I run:

ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
mapper.findAndRegisterModules();
YamlMap ym2 = mapper.readValue(new File("src/main/resources/props.yml"), YamlMap.class);

then I get error:
Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "YamlMap" (class YamlMap)

A quick solution is to add @JsonProperty("mp") above your field :

public class YamlMap {

    @JsonProperty("mp")
    Map<String, String> mp;
}

Jackson core annotation names might be misleading but even though this annotation has Json in its' name - it will work. Jackson can be configured to parse different formats like Yaml or CBOR - but still for mapping you would use core annotations which have Json in their names.

Another solution is to create a constructor and use @JsonCreator :

public class YamlMap {

    Map<String, String> mp;

    @JsonCreator
    public YamlMap(@JsonProperty("mp") Map<String, String> mp) {
        this.mp = mp;
    }
}

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