【问题标题】:Jackson - Json string to Java List of classJackson - Json 字符串到 Java 类列表
【发布时间】:2018-12-06 10:32:05
【问题描述】:

我正在尝试使用 Jackson 将 JSON 字符串映射到 Java 类。

public class ChartData {
    List<String> xAxis=new ArrayList<String>();
    List<String> yAxis=new ArrayList<String>();
    List<String> zAxis=new ArrayList<String>();
    String type;

    public ChartData() {

    }

    public ChartData(String type, List<String> yAxis, List<String> zAxis) {
        this.type = type;
        this.yAxis = yAxis;
        this.zAxis = zAxis;

    }

我试过的代码:

List<ChartData> emp = new ArrayList<>();
String o2 ="[{\"type\": \"2\", \"yAxis\": [\"11\"], \"zAxis\": [\"8\"]}, {\"type\": \"3\", 
             \"yAxis\": [\"17\", \"13\", \"12\"], \"zAxis\": [\"14\", \"13\", \"12\"]}]";
ObjectMapper mapper = new ObjectMapper();
data= (List<ChartData>) mapper.readValue(o2, ChartData.class);

return data;

但是,我收到以下错误:

无法从 START_ARRAY 令牌中反序列化 com.ChartData 的实例 在 [来源:[{“type”:“2”,“yAxis”:[“11”],“zAxis”:[“8”]},{“type”: "3", "yAxis": ["17", "13", "12"], "zAxis": ["14", "13", "12"]}];线: 1、栏目:1]

我的错误在哪里?

【问题讨论】:

    标签: java jackson


    【解决方案1】:

    jackson中有一种特定的方式可以反序列化成list:

    List<ChartData> data = mapper.readValue(o2 , new TypeReference<List<ChartData>>(){});
    

    在您的代码中,您在转换中也存在类型不匹配。您正在使用mapper.readValue(o2, ChartData.class),但您将其转换为List&lt;ChartData&gt;

    要保持基本的类型转换(不带TypeReference),您可以通过以下方式将json反序列化为数组:

    ChartData[] data = mapper.readValue(o2 , ChartData[].class);
    

    然后根据需要将其转换为列表。

    【讨论】:

    • 前 1 个节省了我的时间。
    猜你喜欢
    • 2018-04-01
    • 2016-02-08
    • 1970-01-01
    • 2012-07-04
    • 1970-01-01
    • 2020-05-20
    • 2013-12-25
    • 2017-11-28
    • 1970-01-01
    相关资源
    最近更新 更多