【问题标题】:convert large list to json string将大列表转换为 json 字符串
【发布时间】:2020-05-23 09:27:41
【问题描述】:

我有一个包含 9864284 个元素的列表,我想将此列表转换为 json 字符串,我使用了递归方法,但总是出现 outOfMemory 异常。

public String createRecuJson(List<CustomObject> inputList, int nElement, int index, List<String> result, String resJson) throws Exception {
    ObjectMapper objectMapper = new ObjectMapper();
    if( index + nElement > inputList.size() ) {
        resJson = resJson.concat(","+objectMapper.writeValueAsString(inputList.subList(index,inputList.size())).replace("[", "").replace("]", ""));
        result.add(objectMapper.writeValueAsString(inputList.subList(index,inputList.size())));
        return resJson;
    }else {
        final List<CustomObject> subListCustomObjects = inputList.subList(index, index+nElement);
        if(resJson.length() == 0)
            resJson.concat(objectMapper.writeValueAsString(subListCustomObjects).replace("[", "").replace("]", ""));
        else
            resJson = resJson.concat(","+objectMapper.writeValueAsString(subListCustomObjects).replace("[", "").replace("]", ""));
        result.add(objectMapper.writeValueAsString(subListCustomObjects));
        return createRecuJson(inputList, nElement, index+nElement, result, resJson);
    }
}

【问题讨论】:

  • 我使用 Apache Spark 处理如此大的数据集。即使我只在笔记本电脑上运行它。 Spark 支持 JSON 和 JSON 行。
  • @steven35 你能分享一个例子吗(例如url)我从不使用apache spark
  • 可以尝试使用StringBuilder代替String resJson,然后返回resJson.toString()。同时拥有resJson和result有意义吗?
  • 您自己创建 JSON 有什么具体原因吗?通常,您会使用 JSON-B 之类的东西来完成任务 (javaee.github.io/jsonb-spec/getting-started.html)
  • 4 GB 对于这项工作似乎有点有限,当您使用库而不是专用于大数据集时。可能,这甚至不足以将整个 JSON 保存在内存中......

标签: java json list bigdata


【解决方案1】:

尝试使用Jackson Streaming API 而不是您的实现。它是对 JSON 内容的最低写入权限。

Here你可以找到一些例子。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多