Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is TypeReference in java which is used while converting a JSON script to MAP

Tags:

java

json

While converting a JSON received from api response I came accross TypeRef, but I am not sure how does it works? Any pictorial representation or simplified version will be good. I read, but still not so much clear about it. Like we have map to store <K,V> but then what difference will TypeRef will do on object?

TypeReference<HashMap<String,Object>> typeRef = new TypeReference<HashMap<String,Object>>() {};
like image 904
Kavita Kulkarni Avatar asked Dec 28 '25 00:12

Kavita Kulkarni


1 Answers

In Java generics are more or less gone at runtime. This is called type erasure. So your HashMap<String, Object> will just be HashMap<?, ?> when your programme runs. So Jackson cannot determine the types Stringand Object. That is why you have to create a TypeReference which will preserve that information at runtime so Jackson can deserialise your JSON String into the correct classes.

If you don't specify a type Jackson will still be able to correctly deserialise simple objects like String or numbers but when a more complex object is encountered it will simply deserialise them into LinkedHashMap which will then most likely lead to a ClassCastException when you try to access the deserialised object.

like image 132
geanakuch Avatar answered Dec 30 '25 14:12

geanakuch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!