Jackson Streaming API不会检测脱离上下文的写入

时间:2015-03-30 21:37:46

标签: java json jackson

我使用Jackson 2.5.1(com.fasterxml.jackson.core.JsonGenerator)将JSON文档写入输出流。看起来API允许我们向流写入错误的JSON?我想如果我们尝试在错误的上下文中编写元素,它应该抛出JsonGenerationException或IOException。这是代码片段:

try {
  JsonFactory jfactory = new JsonFactory();
  ByteArrayOutputStream b = new ByteArrayOutputStream();
  JsonGenerator jsonGenerator = jfactory.createJsonGenerator(b, JsonEncoding.UTF8);
  jsonGenerator.writeStartObject();
  jsonGenerator.writeStringField("str1", "blahblah");
  jsonGenerator.writeNumber(1234);
  jsonGenerator.writeEndObject();
  jsonGenerator.close();
  System.out.println(b.toString());
} catch (Exception e) {
  e.printStackTrace();
}

try { JsonFactory jfactory = new JsonFactory(); ByteArrayOutputStream b = new ByteArrayOutputStream(); JsonGenerator jsonGenerator = jfactory.createJsonGenerator(b, JsonEncoding.UTF8); jsonGenerator.writeStartObject(); jsonGenerator.writeStringField("str1", "blahblah"); jsonGenerator.writeNumber(1234); jsonGenerator.writeEndObject(); jsonGenerator.close(); System.out.println(b.toString()); } catch (Exception e) { e.printStackTrace(); } 输出是:{" str1":" blahblah":1234}并且它不是有效的JSON。这是预期的行为还是我遗失了什么?我认为API本身会跟踪对象是否在正确的上下文中编写。它是否需要由应用程序本身强制执行?从文件中不清楚: http://fasterxml.github.io/jackson-core/javadoc/2.0.0/com/fasterxml/jackson/core/JsonGenerator.html

0 个答案:

没有答案