Search code examples
javajsonenumsboon

Boon Json unable to desrialize Enums by common interface


I'm trying to serialize and deserialize through Boon Json a simple Map <Resistance, Double> map = new HashMap(), where Resistance is an interface implemented only by two enum.

public interface Resistance {}

public enum Condition implements Resistance{
    BURN, SLEEP, PARALYZED, CONFUSE;
}

public enum Element implements Resistance{
    FIRE, ICE, EARTH, AIR;
}

after adding some value the serialization seems to work fine:

map.put(Element.FIRE, 1.1);
map.put(Condition.BURN, 0.2);
System.out.println("Fire resistance: " + map.get(Element.FIRE));
System.out.println("Burn resistance: " + map.map.get(Condition.BUR));

ObjectMapper mapper =  JsonFactory.create();
String dst = mapper.toJson(manager);
System.out.println(dst);

Output:

Fire resistance: 1.1
Burn resistance: 0.2
{"map":{"FIRE":1.1,"BURNED":0.2}}

The problem occurs during deserialization, (I think) the parser fails to associate the enumerator with its class. And so I get:

map = mapper.readValue(dst, map.getClass()) ;

System.out.println("Fire resistance: " + manager.get(Element.FIRE));
System.out.println("Burn resistance: " + manager.get(Condition.BURN));

Output:

Fire resistance: null
Burn resistance: null
{"map":{"":0.2}}

How could I fix this?


Solution

  • I am editing my answer:

    //Wrong as map.getClass() returned actual implementation of class

    Map map2 = mapper.readValue(dst, map.getClass()) ;

    //returned correct map

    Map map2 = mapper.readValue(dst,Map.class) ;

    Also change your code that prints to :

    System.out.println("Fire resistance: " + manager.get(Element.FIRE.toString()));
    System.out.println("Burn resistance: " + manager.get(Condition.BURN.toString()));