使用超大的json文件。 总是内存不足

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

ObjectMapper mapper = new ObjectMapper(); Map map = new HashMap(); List list = new ArrayList(); // 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的示例(“阅读和编写事件流”)。

编辑:这应该太难以弄清楚人们…但这是一个骨架的例子:

 // 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();

这应该做的伎俩。