【发布时间】:2014-09-23 19:27:01
【问题描述】:
假设我有一堂课
class A {
public int x;
}
那么可以解析出一个有效的json如下:
ObjectMapper mapper = new ObjectMapper();
A a = mapper.readValue("{\"x\" : 3}", A.class);
如果字符串包含的数据多于解析对象所需的数据,有没有办法让解析器失败?
例如,我希望以下失败(成功)
A a = mapper.readValue("{\"x\" : 3} trailing garbage", A.class);
我尝试使用带有 JsonParser.Feature.AUTO_CLOSE_SOURCE=false 的 InputStream 并检查流是否已被完全消耗,但这不起作用:
A read(String s) throws JsonParseException, JsonMappingException, IOException {
JsonFactory f = new MappingJsonFactory();
f.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
ObjectMapper mapper = new ObjectMapper(f);
InputStream is = new ByteArrayInputStream(s.getBytes(StandardCharsets.UTF_8));
try {
A a = mapper.readValue(is, A.class);
if(is.available() > 0) {
throw new RuntimeException();
}
return a;
} finally {
is.close();
}
}
也就是说,
read("{\"x\" : 3} trailing garbage");
仍然成功,可能是因为解析器从流中消耗的内容超出了严格必要的范围。
一种可行的解决方案是验证从字符串中删除最后一个字符时解析是否失败:
A read(String s) throws JsonParseException, JsonMappingException, IOException {
ObjectMapper mapper = new ObjectMapper();
A a = mapper.readValue(s, A.class);
if (s.length() > 0) {
try {
mapper.readValue(s.substring(0, s.length()-1), A.class);
throw new RuntimeException();
} catch (JsonParseException e) {
}
}
return a;
}
但我正在寻找更有效的解决方案。
【问题讨论】:
-
解决方案对您有用吗?