【问题标题】:How to deserialize a list of lists? [closed]如何反序列化列表列表? [关闭]
【发布时间】:2021-06-21 16:15:43
【问题描述】:

我有一个列表列表"[[2,3,5,7],[1,4,6]]"

如何使用 Jackson 将其转换为 Java ArrayList?任何参考资料或示例都可以。

【问题讨论】:

  • 请告诉我们您尝试过的代码。你有什么问题?
  • 其实我不知道如何解决这个问题,所以我问任何参考也可以工作
  • 我相信谷歌搜索会帮助你。

标签: java jackson


【解决方案1】:

这是使用 objectmapper 反序列化的泛型包装器,

public static <T> T fromJSON(final TypeReference<T> type,
      final String jsonPacket) {
   T data = null;

   try {
      data = new ObjectMapper().readValue(jsonPacket, type);
   } catch (Exception e) {
      // Handle the problem
   }
   return data;

例子

var list = "[[2,3,5,7],[1,4,6]]";
var result = JsonUtils.deserialize(new TypeReference<ArrayList<ArrayList<Integer>>>() {}, list);

【讨论】:

  • 谢谢@Nainesh Patel 的回答
【解决方案2】:

这里是一些使用TypeFactory的示例代码

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import java.util.ArrayList;

class Scratch {
    public static void main(String[] args) throws JsonProcessingException {
        final TypeFactory typeFactory = TypeFactory.defaultInstance();
        final ArrayList<ArrayList<Integer>> data = new ObjectMapper().readValue("[[2,3,5,7],[1,4,6]]",
                typeFactory.constructCollectionType(ArrayList.class,
                        typeFactory.constructCollectionType(ArrayList.class, Integer.class)));
        System.out.println(data);
    }
}

它构建对象并打印

[[2, 3, 5, 7], [1, 4, 6]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-03
    • 1970-01-01
    • 2011-03-26
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 2018-08-17
    相关资源
    最近更新 更多