【问题标题】:How to fix Error START_ARRAY token when deserializing Json with ModelMapper?使用 ModelMapper 反序列化 Json 时如何修复错误 START_ARRAY 令牌?
【发布时间】:2021-12-19 02:38:27
【问题描述】:

我正在尝试以这种格式反序列化 JSON 文件:

[
  ["AA", "GG", "1992/11/18"],
  ["BB", "DD", "2005/02/20"]
]

使用这个类:

public class DataList {
    private List<String> att;
    // constructor, getter and setter
}

在做:

DataList [] dataList= mapper.readValue(ResourceUtils.getFile("classpath:" + filename), DataList [].class);

但我得到:

    com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `org.example.DataList ` out of START_ARRAY token
 at [Source: (File); line: 2, column: 3] (through reference chain: java.lang.Object[][0])

知道如何解决这个错误吗?

【问题讨论】:

    标签: java json serialization deserialization modelmapper


    【解决方案1】:

    Jackson 不知道如何将字符串数组映射到 DataList 对象。因此,您只需在 DataList 构造函数上添加 @JsonCreate 即可向 Jackson 展示用于转换的内容。

    public class DataList {
    
        private List<String> att;
    
        @JsonCreator
        public DataList(List<String> att) {
            this.att = att;
        }
    
        // constructor, getter and setter
    }
    

    【讨论】:

    • 我试过了,但同样的错误又发生了。
    • @jimmy,请指定您的Jackson 版本。您也可以尝试仅使用原始字符串(不从文件中读取 json)运行代码,以确保它不是问题的一部分。
    • 有一个错字,您的解决方案有效!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2020-12-12
    • 2020-04-03
    • 2014-06-11
    • 2020-07-14
    • 2020-04-18
    • 2019-04-28
    • 1970-01-01
    • 2020-06-16
    相关资源
    最近更新 更多