Fastjson API Stream


Fastjson requires Stream API when it needs to process very large JSON text. The Stream API will be provided in fastjson-1.1.32 version.

Serialization

Extremely large JSON array serialization

If Your JSON format is a huge JSON array with many elements. First call startArray, then write objects one by one, and then call endArray.

  JSONWriter writer = new JSONWriter(new FileWriter("/tmp/huge.json"));
  writer.startArray();  for (int i = 0; i < 1000 * 1000; ++i) {
        writer.writeValue(new VO());
  }
  writer.endArray();
  writer.close();

Serialization of very large JSON objects

If your JSON format is a huge JSONObject with many Key/Value pairs, first Call startObject, then write Key and Value one by one, and then call endObject.

 JSONWriter writer = new JSONWriter(new FileWriter("/tmp/huge.json"));
 writer.startObject();
 for (int i = 0; i < 1000 * 1000; ++i) {
       writer.writeKey("x" + i);
       writer.writeValue(new VO());
 }
 writer.endObject();
 writer.close();

Deserialization

  JSONReader reader = new JSONReader(new FileReader("/tmp/huge.json"));
  reader.startArray();
  while(reader.hasNext()) {
        VO vo = reader.readObject(VO.class);
        // handle vo ...
  }
  reader.endArray();
  reader.close();

  JSONReader reader = new JSONReader(new FileReader("/tmp/huge.json"));
  reader.startObject();
  while(reader.hasNext()) {
        String key = reader.readString();
        VO vo = reader.readObject(VO.class);
        // handle vo ...
  }
  reader.endObject();
  reader.close();