0

I would like to deserialize a json string to a java object. 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:

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

Whereas, when in call the commented deSerial method, it works fine. Please explain the issue.

Thanks.

6
  • 2
    I don't see the point for using a generic here. Just pass the desired class to deSerialize, so calling it like deSerialize(json, Person.class);. Much easier, less boilerplate. Commented Feb 15, 2019 at 9:47
  • HI @Tom, Tomorrow I want to use with Employee.class how would I use it? I don't want to write another method for Employee.class Commented Feb 15, 2019 at 9:47
  • @Raghu use Class<T>? exactly the same way ObjectMapper already does to allow you to make JSONs into objects. Commented Feb 15, 2019 at 9:49
  • use deSerialize(json,class<T> clazz) for generic Commented Feb 15, 2019 at 9:51
  • @SHAHAKASH Your comment is wrong. You're mixing a method definition and the method call. Commented Feb 15, 2019 at 9:55

1 Answer 1

4

Jackson doesn't support TypeReference with generic type parameters because of type erasure. Here's the bug about it.

As far as your use case is concerned, you don't need to use ObjectSerializer class at all. You can directly expose ObjectMapper object to your service layer and perform the deserialization.

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Person person = mapper.readValue(inputJson,Person.class); Thanks. Accepted the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.