且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 gson 将 json 解析为 java 对象的问题

更新时间:2023-01-17 16:13:01

没有看到 CommunicationObject 的代码,我不能肯定但我有信心地猜测该类有一个字段IsBean 类型,您可以在其中使用它来保存 User.如果是这样,问题是 GSON 会扫描 CommunicationObject 类的对象 obj 的字段,并根据字段定义,字段的值(类型为 IsBean) 将必须被创建,但由于类型是一个接口,它不能为该字段创建实例对象.

Without seeing the code of CommunicationObject, I can't say for sure BUT I am guessing with confidence that the class has a field of type IsBean in which you use it to hold the User. If so, the problem is that GSON scans fields of the object obj of the class CommunicationObject and based on the field definition, the value of the field (which is typed IsBean) will have to be created BUT since the type is an interface, it can't instance object for that field.

换句话说,由于 JSON 字段没有指定对象类型,GSON 必须依赖于定义的字段类型来为字段值创建实例,如果类型是接口,则无法实现.

Another words, as JSON field does not specifies the object type, GSON must relies on the defined type of the field to create the instance for the field value which can't be done if the type is an interface.

因此,如果您觉得有意义,请考虑更改该字段的类型.或者考虑创建 InstanceCreatorIsBean(怀疑它在逻辑上是可能的).

So, consider changing the type of that field if that make sense to you. OR look into creating InstanceCreator of IsBean (doute that it is logically possible).

另见:在 Gson 中反序列化抽象类

希望这会有所帮助.