[英]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:这是 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)线程“main”com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException 中的异常:无法识别的字段“YamlMap”(YamlMap 类)
A quick solution is to add @JsonProperty("mp")
above your field :一个快速的解决方案是在您的字段上方添加
@JsonProperty("mp")
:
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 核心注释名称可能具有误导性,但即使此注释的名称中包含Json - 它也会起作用。 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.
Jackson 可以配置为解析不同的格式,如 Yaml 或 CBOR - 但对于映射,您仍将使用名称中包含Json 的核心注释。
Another solution is to create a constructor and use @JsonCreator
:另一种解决方案是创建一个构造函数并使用
@JsonCreator
:
public class YamlMap {
Map<String, String> mp;
@JsonCreator
public YamlMap(@JsonProperty("mp") Map<String, String> mp) {
this.mp = mp;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.