我正在使用带有StringWriter的com.google.gson.stream.JsonWriter来编写一个有点长的JSON。
StringWriter stringWriter = new StringWriter();
JsonWriter jsonWriter = new JsonWriter(stringWriter);
然后迭代集合并编写JSON。
jsonWriter.name("Elements").beginArray();
Collection<Element> collection = someObject.getCollection();
for(Element e : collection){
jsonWriter.beginObject()
.name("Id").value(e.getId())
.endObject();
}
jsonWriter.endArray();
我的问题是,当我尝试关闭编写器时,我得到一个 IOException:Incomplete Document。而且似乎流无法刷新所有数据或其他东西,因为JSON在中间结束一个元素。
像这样:
{
"Id": "1245
Collection实际上是 HashMap.values()。我有预感,因为HashMap没有同步或类似的东西。
编辑:我正在关闭作家并以这种方式获取字符串:
jsonWriter.flush();
jsonWriter.close();
String json = stringWriter.toString();