gpt4 book ai didi

java - 使用超大的 json 文件。返回总是内存不足

转载 作者:搜寻专家 更新时间:2023-11-01 03:40:45 27 4
gpt4 key购买 nike

jackson如何使用stream API json?请参阅下面的代码:

    ObjectMapper mapper = new ObjectMapper();

Map<String, Object> map = new HashMap<String, Object>();

List<Object> list = new ArrayList<Object>();

// Get images in database
try {
Class.forName(DRIVER);
connection = DriverManager.getConnection(URL, USER, PASSWORD);

Statement s = connection.createStatement();
ResultSet r = s.executeQuery("select * from images");

while (r.next()) {

byte[] imageBytes = r.getBytes("image");
String imageBase64 = DatatypeConverter.printBase64Binary(imageBytes);
list.add(imageBase64);
}

} catch (SQLException e) {

}

map.put("images", list);

// Stream Json API
try {
mapper.writeValue(new File("c:\\images.json"), map);
} catch (JsonGenerationException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

总是返回内存不足。我不知道在 jackson 身上使用流媒体。我使用超大 json,平均 2000 张图像,每张图像一个 imageBase64。我做错了什么?

最佳答案

不是将所有图像都保存在内存中,而是增量地读取和写入它们。可以找到 Jackson Streaming API 的示例 here (“读写事件流”)。

编辑:这应该很难让人理解......但这是一个基本的例子:

// typed from memory, some methods may be off a bit
JsonFactory f = objectMapper.getFactory();
JsonGenerator gen = f.createGenerator(new File("c:\\images.json"));
gen.writeStartArray(); // to get array of objects
// get the DB connection etc
while (r.next()) {
gen.writeFieldName("image");
InputStream in = r.getBinaryStream("image");
gen.writeBinary(in, -1); // length optional for JSON
in.close();
}

gen.writeEndArray();//获取对象数组 gen.close();

这应该可以解决问题。

关于java - 使用超大的 json 文件。返回总是内存不足,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15097939/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com