杰克逊如何将json反序列化为泛型类型?

时间:2017-07-18 08:33:57

标签: java generics jackson deserialization

类人物:

@Data
public class Person<T extends Parent> implements Serializable {
    private static final long serialVersionUID = 7822965786010192978L;

    private static final ObjectMapper objectMapper = new ObjectMapper();  
    private String id;    
    private T people; // change (String peopleInfo) to object extends Parent after read data from database
    private String peopleInfo; // change (T people) to string and save in the dataBase as an string

    @SneakyThrows
    public void setPeople(T people) {
        this.people = people;
        peopleInfo = objectMapper.writeValueAsString(people);
    }

    @SneakyThrows
    public void setPeopleInfo(String peopleInfo) {
        this.peopleInfo = peopleInfo;
        if (!Strings.isNullOrEmpty(peopleInfo)) {
            people = objectMapper.readValue(peopleInfo, new TypeReference<T>() {});
        }
    }
}

class Parent:

@Data
public class Parent implements Serializable {
    private static final long serialVersionUID = 2092353331893381153L;
    private String name;
}

class Child:

@Data
public class Child extends Parent {
    private static final long serialVersionUID = 3318503314202792570L;
    private String pocketMoney;
}

和测试函数:我想将persnInfo保存到数据库String,并在从数据库中读取数据后自动将此string更改为对象people

@Test
public void testReadData() throws Exception {
    Child child = new Child();
    child.setName("_child");
    child.setPocketMoney("10$");

    Person<Child> person = new Person<>();
    person.setId("1");
    person.setPeople(child);

    // assume this json was read from database
    String json = person.getPeopleInfo();
    System.out.println(json);

    Person<Child> readPerson = new Person<>();
    readPerson.setId("1");
    readPerson.setPeopleInfo(json);

    Child readChild = readPerson.getPeople();
    System.out.println(readChild.getPocketMoney());
}

错误发生了:

  

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:无法识别的字段“pocketMoney”(类pers.test.common.objmapper.Parent),未标记为可忽略(一个已知属性:“name”))

     

at [来源:{“name”:“_ child”,“pocketMoney”:“10 $”}; line:1,column:33](通过引用链:pers.test.common.objmapper.Parent [“pocketMoney”])

     

at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:51)

我不知道要解决这个问题,任何人都可以帮助我通过而不更改testReadData()' but change the model人员。

1 个答案:

答案 0 :(得分:3)

你的问题在这里:

new TypeReference<T>()

这并不是你所期望的。 Java泛型在运行时被擦除;因此,上述陈述基本上是new TypeReference<Object>

换句话说 - 您宣布

的事实
Person<Child> readPerson = new Person<>();

期待子对象是不够的!

您可能必须将特定的类Child.class传递给映射JSON字符串的代码。有关详细信息,请查看here