我有办法让 Jackson 对输入的 JSON 不那么严格吗?例如。 JSONObject 提供以下津贴:
The constructors are more forgiving in the texts they will accept:
- An extra , (comma) may appear just before the closing brace.
- Strings may be quoted with ' (single quote).
- Strings do not need to be quoted at all if they do not begin with a quote or single quote, and if they do not contain leading or trailing spaces, and if they do not contain any of these characters: { } [ ] / \ : , = ; # and if they do not look like numbers and if they are not the reserved words true, false, or null.*
- Keys can be followed by = or => as well as by :.
- Values can be followed by ; (semicolon) as well as by , (comma).
- Numbers may have the 0x- (hex) prefix.
对我来说最有趣的是第三点。它允许进行以下转换:
new JSONObject("{A : 1}");
...但是对于 jackson,我会收到相同输入 json 的错误:
new ObjectMapper().readTree("{ A : 1}"); // throws an exception
异常(exception):
org.codehaus.jackson.JsonParseException: Unexpected character ('A' (code 65)): was expecting double-quote to start field name
at [Source: java.io.StringReader@26d4f1; line: 1, column: 4]
at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:943)
at org.codehaus.jackson.impl.JsonParserBase._reportError(JsonParserBase.java:636)
at org.codehaus.jackson.impl.JsonParserBase._reportUnexpectedChar(JsonParserBase.java:569)
at org.codehaus.jackson.impl.ReaderBasedParser._handleUnusualFieldName(ReaderBasedParser.java:342)
at org.codehaus.jackson.impl.ReaderBasedParser._parseFieldName(ReaderBasedParser.java:235)
at org.codehaus.jackson.impl.ReaderBasedParser.nextToken(ReaderBasedParser.java:125)
at org.codehaus.jackson.map.deser.BaseNodeDeserializer.deserializeObject(JsonNodeDeserializer.java:180)
at org.codehaus.jackson.map.deser.BaseNodeDeserializer.deserializeAny(JsonNodeDeserializer.java:210)
at org.codehaus.jackson.map.deser.JsonNodeDeserializer.deserialize(JsonNodeDeserializer.java:52)
at org.codehaus.jackson.map.deser.JsonNodeDeserializer.deserialize(JsonNodeDeserializer.java:13)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:1588)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1130)
最佳答案
非标准 JSON 的扩展列表(即不是 JSON,但足够接近以支持它的东西)可以从以下位置找到:http://wiki.fasterxml.com/JacksonFeaturesNonStandard
从您的列表中,(2) 和 (3) 可以完成(加上其他几项未列出的事情,例如 commnet)。其他不支持;尽管项目增加了对一些常用扩展的支持,但考虑的内容是有限的。当然,总是可以要求新功能;根据请求和用例添加功能。
在我个人看来,要么遵循标准,要么定义新格式——HTML 是一个很好的例子,当人们试图支持“几乎但不完全”有效的东西时,HTML 就是一个很好的例子。调整永无止境,互操作性受到影响:由于没有标准,所有实现都支持一些不兼容的功能和构造子集。
关于java - 让 Jackson 对输入 JSON 更友好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5637107/