简体   繁体   English

Java:如何创建参数化的Jackson Json到对象函数

[英]Java: How to Create Parameterized Jackson Json to Object Function

I am trying to serialize objects to and deserialize from json. 我正在尝试将对象序列化为json和从json反序列化。 I tried to make a class with a static method that would accomplish this in the general case given a class. 我试图用静态方法创建一个类,该方法通常会在给定类的情况下完成此操作。

public static <T> T jsonToObject(String json, Class<T> tClass) {
    try {
        return mapper.readValue(json, tClass);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

Then in a unit test: 然后在单元测试中:

@Test
public void testUserDataSerialization() {

    UserData userData = new UserData
        .Builder("david@davidgeorgewilliams.com")
        .firstName("david")
        .lastName("Williams")
        .build();

    String userDataJson = JsonUtils.objectToJson(userData);

    String userDataJson1 = JsonUtils.objectToJson(userData1);

    System.out.println(userDataJson + "\n" + userData1);
} 

This blows up with this exception 这个异常炸死了

Running com.company.app.UserDataJsonTest
org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class com.company.app.model.UserData]: can not instantiate from JSON object (need to add/enable type information?)
at [Source: java.io.StringReader@76ba6b2; line: 1, column: 2]
at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObjectUsingNonDefault(BeanDeserializer.java:746)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:683)

What am I doing wrong here and how do I fix it? 我在这里做错什么以及如何解决? The idea is I want to accept JSON from a post request body, and turn it into the corresponding object. 我的想法是我想从发布请求正文中接受JSON,然后将其转换为相应的对象。

You need to use TypeReference to handle type erasure with generics. 您需要使用TypeReference来处理泛型的类型擦除。 Check out the documentation (the Data Binding with Generics section). 查阅文档 (“使用泛型进行数据绑定”部分)。 TypeFactory works as well. TypeFactory也可以。

答案如上所述。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM