有没有GSON的方法是“不宽松”在所有? [英] Is there a way of GSON to be "not lenient" at all?

查看:102
本文介绍了有没有GSON的方法是“不宽松”在所有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看来GSON在默认情况下会忽略JSON字符串包含的字段名称与目标POJO类别不匹配。一个解决方案概述此处建议使用注释来标记必需字段当对不包含字段的字符串进行反序列化时,GSON会失败。

但是我们定义我们的POJO必须是精确匹配(当我们允许传入对象为空,它们必须在POJO中声明为可选字段 - 并且我们有一个特殊类型的适配器,它将空值变为Optional.empty()实例)。因此POJO中的所有字段都是强制性的。



按照我所关联的问题的指导,似乎只有 的方式让gson分析失败时:对由反序列化过程创建的对象执行完整的深度反射扫描,并检查任何可选字段是否为空。



或者也许 - 我错过了一些东西,当我们的JSON字符串包含错误的字段名称时,有更简单的方法让gson 告诉我



(背景:我们只是遇到了一个问题,因为嵌套结构中的字段名称错误 - 导致null对象在我们不期望的地方)

解决方案

结果:这个缺陷实际上是gson的核心设计点:它是一个JSON 解析器 。在gson的范围内验证是 not



因此,正确的答案是使用 java bean validation 注释并放置一些实现框架(例如 hibernate validator apache bval )。



另外,创建gson实例时可以注册一个特殊类型的适配器。这种类型的适配器使用反射通过一些检查代码覆盖内部映射 - 允许相对干净的解决方案,导致gson在运行到未知字段时抛出异常。 (感谢 Andy Turner 指向相应的 github issue tracker 条目---代码可以在那里找到)


It seems that GSON silently ignores when a JSON string contains field names that don't match the target POJO class. One solution outlined here suggests to use annotations to mark "required" fields to have GSON fail when de-serializing strings that don't contain fields.

But we defined that our POJOs must be "exact" matches (when we allow for incoming objects to be null, they must be declared as Optional field in the POJO - and we have a special type adapter that turns nulls into Optional.empty() instances). Therefore all fields in the POJO are mandatory. And null isn't a valid value.

Following the guidance in that question I linked to, it seems that the only way of having gson fail while parsing: to do a full "deep reflection" scan of the object created by de-serialization process and check if any of the Optional fields are null.

Or maybe - I am missing something and there is an easier way to have gson tell me when our JSON strings contain bad field names?

( background: we just ran into a problem because of wrong field name deep down in a nested structure - leading to null objects where we didn't expect them )

解决方案

Turns out: this "deficiency" is really a core design point of gson: it is a JSON parser. Validation is not within the scope of gson.

Therefore the "correct" answer is to use java bean validation annotations and to put some implementation framework (for example the hibernate validator or apache bval) in place.

Alternatively, it is possible to register a special type adapter when creating the gson instance. This type adapter uses reflection to override an internal map with a bit of checking code - allowing for a relatively "clean" solution which leads to gson throwing an exception when running into "unknown" fields. ( thanks to Andy Turner for pointing to the corresponding github issue tracker entry --- code can be found there)

这篇关于有没有GSON的方法是“不宽松”在所有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆