Boon Json无法通过通用接口对Enums进行反序列化

时间:2017-09-27 09:39:19

标签: java json enums boon

我试图通过Boon Json序列化和反序列化一个简单的Map <Resistance, Double> map = new HashMap(),其中Resistance是一个仅由两个枚举实现的接口。

public interface Resistance {}

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

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

添加一些值后,序列化似乎工作正常:

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);

输出:

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

在反序列化期间出现问题,(我认为)解析器无法将枚举器与其类关联。所以我得到了:

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

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

输出:

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

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我正在编辑我的回答:

//错误的map.getClass()返回了类

的实际实现

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

//返回正确的地图

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

同时将您打印的代码更改为:

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