【问题标题】:jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.lang.Stringjackson.databind.exc.MismatchedInputException:无法反序列化 java.lang.String 的实例
【发布时间】:2018-03-14 05:59:12
【问题描述】:

我有一个要读入 Map 的 yaml 文件:

events:
  key1: val1
  key2: val2
  key3: val3


public class EventGenerator {    
  private Map<String, String> events;

  public Map<String, String> getEvents() {
    return this.events;
  }

  public void setEvents() {
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
        try {
            FileInputStream fis = new FileInputStream("file.yaml");
            EventGenerator eventGenerator = mapper.readValue(fis, EventGenerator.class);
            fis.close();
            System.out.print(eventGenerator.getEvents());
        } catch (IOException e) {
            e.printStackTrace();
        }

  }

}

这段代码运行良好。但是当我将 yaml 文件的路径作为字符串参数传递时

public void setEvents(String filePath) {
// same code
FileInputStream fis = new FileInputStream(filePath)
// same code
}

我遇到了异常

jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of java.lang.String

谁能解释这种行为以及我在这里做错了什么?

【问题讨论】:

  • 请提供路径变量的值。
  • System.getProperty("user.dir") + "/src/main/resources/file.yaml"这两种情况都是一样的。

标签: java hashmap jackson yaml


【解决方案1】:

已解决问题。 Setter 方法必须遵循严格的 POJO 标准,即setEvents(Map events) {this.events = events};,并且反串必须进入另一个方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-06
    • 2017-08-25
    • 2015-03-10
    • 2019-06-01
    • 2013-10-23
    • 1970-01-01
    • 2019-12-13
    • 2019-02-08
    相关资源
    最近更新 更多