简体   繁体   English

Java泛型:将JSON转换为Java对象的对象映射器

[英]Java Generics : Object Mapper Converting JSON to Java Object

I would like to deserialize a json string to a java object. 我想将json字符串反序列化为java对象。 I wanted to write a generic method. 我想写一个通用方法。

public class ObjectSerializer<T> {

    T t;
    private ObjectMapper mapper = new ObjectMapper();


  /*  public Person deSerial(String json) throws Exception {
        TypeReference<Person> typeRef = new TypeReference<Person>() {};

        return mapper.readValue(json, typeRef);
    } */

    public T deSerialize(String jsonInput) throws Exception {
        TypeReference<T> typeRef
                = new TypeReference<T>() {};

       return mapper.readValue(jsonInput, typeRef);
    }
}

When I call deSerialize(validPersonJsonString) [validPersonJsonString : valid person JSON String] , it is not working, it it throwing me the error: 当我调用deSerialize(validPersonJsonString) [validPersonJsonString : valid person JSON String] ,它不起作用,它deSerialize(validPersonJsonString) [validPersonJsonString : valid person JSON String]了以下错误:

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.example.Person.

Whereas, when in call the commented deSerial method, it works fine. 而在调用带注释的deSerial方法时,它可以正常工作。 Please explain the issue. 请说明问题。

Thanks. 谢谢。

Jackson doesn't support TypeReference with generic type parameters because of type erasure. 由于类型擦除,Jackson不支持带有泛型类型参数的TypeReference Here's the bug about it. 这是关于它的错误。

As far as your use case is concerned, you don't need to use ObjectSerializer class at all. 就您的用例而言,您根本不需要使用ObjectSerializer类。 You can directly expose ObjectMapper object to your service layer and perform the deserialization. 您可以将ObjectMapper对象直接暴露给服务层并执行反序列化。

If you want to shield the json serializing mechanism from your service layer then you can wrap ObjectMapper implementation into another class (like you have done in your code) but then, accept the class type as a method argument rather than a generic type. 如果要从服务层屏蔽json序列化机制,则可以将ObjectMapper实现包装到另一个类中(就像您在代码中所做的一样),但是然后将类类型作为方法参数而不是泛型类型接受。

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

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