通过 Jackson 进行 JSON 重复属性验证
我使用 Jackson 并且想要检查输入 JSON 字符串是否不包含重复的属性,例如:
{"a" : 1, "a" : 0}
按照 Jackson 片段处理输入字符串,没有任何错误,甚至返回值:
<代码> JsonNode jsonSelect = mapper.readTree("{ A: 1, A: 0}"); System.out.println(jsonSelect.getFieldValue("A")); // 打印0
我有机会通过 Jackson 验证重复项吗?
PS JSON 格式是否支持重复属性?我在规范中没有找到任何关于它的限制。另外 org.json.JSONObject 会引发重复项的异常,但没有给我答案 - 是 {"a" : 1, "a" : 0}
好吧 -按标准形成。
I use Jackson and want to check that input JSON string doesn't contain duplicated properties like:
{"a" : 1, "a" : 0}
Following Jackson fragment process input string without any errors and even return value:
JsonNode jsonSelect = mapper.readTree("{ A : 1, A : 0}");
System.out.println(jsonSelect.getFieldValue("A")); // prints 0
Does I have a chance to validate duplicates via Jackson?
P.S. Does JSON format support duplicated properties at all? I didn't find any restrictions about it in specification. Also org.json.JSONObject
throws an exception for duplicates that doesn't give me an answer - is {"a" : 1, "a" : 0}
well-formed according to standard.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
JSON 规范表明重复项不被视为有效,但解析器不需要对它们执行任何操作。从实际角度来看,跟踪所有可见的属性会增加开销,这在流解析器级别可能没有意义。
至于杰克逊,它曾经在数据绑定级别进行重复检测,但我认为目前尚未启用。在处理地图时可以相当容易地添加它。
如果这是您想要的,提交功能请求或询问用户列表可能是有意义的(特别是看看其他人是否也想要此功能,使其更有可能很快添加)。
如果您只想验证,您可以创建一个 Map 子类,使其在重复时抛出异常。或者,只需在子类中设置一个标志,您可以根据需要进行检查。
JSON specification indicates duplicates are not consider valid, but parsers are not required to do anything about them. From practical perspective, keeping track of all seen properties adds overhead, which may not make sense at streaming parser level.
As to Jackson, it used to have duplicate detection at data binding level, but I think that is not enabled at this point. It could be added fairly easily when dealing with Maps.
If this is something you would want, filing a feature request or asking on user list might make sense (esp. to see if others would want this feature too, making it more likely to get added soon).
If all you want to do is just validation, you could create a Map subclass, make it throw exception on duplicate. Or, just set a flag in sub-class that you can check if you prefer.
JSON 不支持重复的属性。因此,如果您的输入保证是有效的 JSON,则无需检查它们。
JSON does not support duplicated properties. So if your input is guaranteed to be valid JSON you don't have to check for them.