我有一个包含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);
}
}
最佳答案
尝试使用Jackson Streaming API
代替您的实现。这是对JSON内容的最低级别的写访问。
Here您可以找到一些示例。