Note that there are some explanatory texts on larger screens.

plurals
  1. POJackson - deserialize into runtime specified class
    text
    copied!<p>I'm writing a class that uses Jackson to serialize/deserialize objects. At compile time I don't know which is the type of the objects I will be serializing/deserializing.</p> <p>I read a couple of articles and questions about the usages of <code>TypeReference</code> and <code>TypeFactory</code>, however I'm still having some issues.</p> <p>My class looks like (removed some irrelevant code):</p> <pre><code>public class JsonSerializer&lt;T&gt; { private ObjectMapper objectMapper; private TypeReference typeReference; @PostConstruct public void init() { objectMapper = new ObjectMapper(); typeReference = new TypeReference&lt;T&gt;(){ }; } // ... public Object decode(CachedData cachedData) { try { return objectMapper.readValue(cachedData.getData(), typeReference); } // ... } } </code></pre> <p>And this is the snippet of code I'm using to test this:</p> <pre><code>public class SerializerTest { private JsonSerializer&lt;Clazz&gt; serializer; private ObjectMapper objectMapper = new ObjectMapper(); private static final String CHARSET = "UTF-8"; private Clazz data = generateData(); // creates a simple object @BeforeMethod public void beforeMethod() { serializer = new JsonSerializer&lt;Clazz&gt;(); serializer.init(); } // ... public void shouldDecodeDataCorrectly() throws Exception { CachedData cachedData = new CachedData(0, objectMapper.writeValueAsString(data).getBytes(CHARSET), CachedData.MAX_SIZE); Object object = serializer.decode(cachedData); assertEquals(data, object); } public static class Clazz { // POJO with getters and setters } } </code></pre> <p>As far as I could understand, using <code>typeReference</code> should be enough to let know the deserializer that the value read from the byte stream should be put in a <code>Clazz</code> object. However, the object returned by the <code>decode()</code> method is still a <code>Map</code>, which I understand is the default class for deserializing.</p> <p>I tried also changing the <code>decode()</code> method to return <code>return objectMapper.readValue(cachedData.getData(), objectMapper.getTypeFactory().constructType(typeReference))</code>, but I'm getting the same problem.</p> <p>I'm quite sure it's something regarding the way I pass the type into the serializer, but I haven't been able so far to fix it. Thanks.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload