tags:

views:

33

answers:

1

Hi All

I have a really annoying problem , please take a look at the code:

    ObjectMapper mapper = new ObjectMapper();
    List<Message> messageList = new ArrayList<Message>();
    messageList.add(new RoomTextMessage(1,"2","22",1));
    messageList.add(new PresenceMessage(1,1,2, UserStatus.OFFLINE));
    mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_CONCRETE_AND_ARRAYS);
    String s = mapper.writeValueAsString(messageList);


    mapper.convertValue(s,???)

RoomTextMessage , and PresenceMessage extend Message.

So when I print out s after writeValueAsString , this is what I get :

[["com.delver.chateau.message.RoomTextMessage",{"text":"22","roomId":"2","userId":1,"sequence":1}],["com.delver.chateau.message.PresenceMessage",{"friendId":2,"status":"OFFLINE","userId":1,"sequence":1}]]

I have no idea how to covert it back to the arrayList , I have almost every API the ObjectMapper has.

A little help would be very appreciated.

A: 

Due to Java Type Erasure it is NOT possible to specify generic types to bind to. In order to pass full generics type information to bind JSON into List, you have to use methods that take either TypeReference or JavaType, like so:

List<Message> result = mapper.readValue(s, new TypeReference<List<Message>>() { });

to use JavaType, you need to construct method by passing java.lang.reflect.Type into TypeFactory (check out JavaDocs for details), respectively:

List<Message> result = mapper.readValue(s, TypeFactory.collectionType(ArrayList.class, Message.class));

if you don't like anonymous inner classes (you can similarly construct all kinds of generics types, with TypeFactory.parametericType(...)).

Jeroen Rosenberg
This is the fist thing I have tried , unfortunately this wont work. But nevermind , I have made it work actually with that , that I am sending over actual arrays, and then Json would include type info in each array bucket.
Roman