猿问

将 JSON 字符串反序列化为具有接口数据成员的 Java 对象时出错

我有一个 JSON 字符串,我想将它反序列化为一个带有接口数据成员的 Java 对象。Java 对象如下所示:


public class Person {

     private String id;

     private String name;

     private AddressInterface addr;

}

Person 和 AddressInterface 都是第三方类,所以我无法对它们进行任何更改。


当我使用以下反序列化 JSON 字符串时,


 objectMapper.readValue(json_file, Person.class)  

我得到以下异常。这是因为对象映射器不知道如何反序列化 AddressInterface 字段。在这种情况下,有人可以让我知道如何将字符串反序列化为 Person 对象吗?非常感谢。


 abstract types either need to be mapped to 

 concrete types, have custom deserializer, 

 or be instantiated with additional type information


炎炎设计
浏览 156回答 3
3回答

摇曳的蔷薇

AddressInterface是一个接口,被认为是抽象的。Foo和两个类Bar都可以实现AddressInterface,但它无法判断应该将数据反序列化为哪一个。可能有效的随机想法:将接口放在包装器中。我只是在猜测,因为我不知道图书馆的背景,但也许是这样的。这里可能还有一些错别字,但它显示了总体思路。&nbsp; &nbsp; public class AbstractSerializable<T> implements Deserialize {&nbsp; &nbsp; &nbsp; &nbsp; private final String className;&nbsp; &nbsp; &nbsp; &nbsp; private T obj;&nbsp; &nbsp; &nbsp; &nbsp; public AbstractSerializable(T obj) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.obj = obj;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; this.className = obj.getClass().getCardinalName();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public AbstractSerializable deserialize(ObjectMapper objectMapper) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;String clazz = input.readNext(String.class);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return objectMapper.readNext(Class.forName(clazz));&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }编辑:如果您尝试将 lambda 放入其中,这可能会中断。编辑 2:&nbsp;@Hadi 注意是正确的,Gson 会让一些事情变得更容易,但是它会遇到同样的问题。我确实找到了这篇文章,它解释了如何在使用 Gson 时修复它。它对我的回答使用了类似的方法,但他们有更好的解释。

呼如林

问题是反序列化 AddressInterface 属性,因为它是一个接口,我认为 objectMapper 正在尝试初始化它的默认构造函数,如下所示addr = new AddressInterface();您可以创建一个继承 AddressInterface 的空具体类并使用它代替 AddressInterfacepublic class Adress implements AddressInterface {...}public class Person {&nbsp;private String id;&nbsp;private String name;&nbsp;private Adress addr;}

Smart猫小萌

使用GSON库,您可以摆脱样板代码!您可以在下面的链接中使用 GSON 库!https://www.tutorialspoint.com/gson/gson_quick_guide.htm
随时随地看视频慕课网APP

相关分类

Java
我要回答