简体   繁体   中英

Java: How to Create Parameterized Jackson Json to Object Function

I am trying to serialize objects to and deserialize from 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.

You need to use TypeReference to handle type erasure with generics. Check out the documentation (the Data Binding with Generics section). TypeFactory works as well.

答案如上所述。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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