简体   繁体   English

Jackson 为空时反序列化 Yaml Map

[英]Jackson deserialize Yaml Map when it is empty

I am trying to deserialize YAML map to Java Map of simple String keys and values for these cases:我正在尝试将 YAML map 反序列化为 Java Z46F3EA056CAA3126B91F3F70BEEA068 的简单字符串值:C

myMap:
  key: value
myMap:
#  key: value

Here's the Java Pojo to create after deserialization:这是反序列化后要创建的 Java Pojo:

class Config {

 @JsonProperty Map<String, String> myMap;

 public Config() {}

 public Config(Map<String, String> myMap) { this.myMap = myMap; }

 public Map<String, String> getMyMap() { return myMap; }

 @Override
 public String toString() {
   return "Config{" + "map=" + myMap + '}';
 }
}

And the main is:主要是:

public static void main(String[] args) throws IOException {

  ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
  String yaml = ".."

  Config config = mapper.readValue(yaml, Config.class);
  System.out.println(config);
}

The project uses these dependencies:该项目使用这些依赖项:

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.1.4</version>
</dependency>
<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-yaml</artifactId>
  <version>2.1.4</version>
</dependency>

In case of yaml = "myMap:\n" + " key: somevalue" , the deserialization works fine, and we can see Config{myMap={key=somevalue}}yaml = "myMap:\n" + " key: somevalue"的情况下,反序列化工作正常,我们可以看到Config{myMap={key=somevalue}}

In case of yaml = "myMap:\n" + "";如果是yaml = "myMap:\n" + ""; (empty or commented entries), Jackson logs these errors: (空或注释条目),Jackson 记录这些错误:

Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not instantiate value of type [map type; class java.util.LinkedHashMap, [simple type, class java.lang.String] -> [simple type, class java.lang.String]] from String value; no single-String constructor/factory method (through reference chain: com.example.Config["myMap"])...

How can I do to manage the case where the lines are commented or there are no provided key/value pairs?我该如何管理注释行或没有提供键/值对的情况?

A YAML block-style map, like the one you use, is implicitly started with the first key/value pair. YAML 块式 map 与您使用的一样,隐含地从第一个键/值对开始。 Therefore, in absence of key/value pairs, no map is started – the value of myMap will be the empty scalar.因此,在没有键/值对的情况下,不会启动 map - myMap的值将是空标量。 An empty scalar is loaded as empty string by Jackson, which leads to the error. Jackson 将空标量加载为空字符串,这会导致错误。

To mitigate this, you need to explicitly set the value to the empty map:为了缓解这种情况,您需要将该值显式设置为空 map:

myMap: {}

{} is a flow-style empty map. {}是流式空 map。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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