【问题标题】:Boon Json unable to desrialize Enums by common interfaceBoon Json 无法通过通用接口反序列化枚举
【发布时间】:2017-09-27 09:39:19
【问题描述】:

我正在尝试通过 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}}

我该如何解决这个问题?

【问题讨论】:

    标签: java json enums boon


    【解决方案1】:

    我正在编辑我的答案:

    //错误为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()));
    

    【讨论】:

    • 所以我应该使用带有String作为键的Map,或者每次都使用valueOf()
    • 现在我得到了java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Enum 我仍然需要使用 toString
    • 是的,你是对的。旧的还是需要的。不知何故,它在编辑我的答案时被删除了
    • 谢谢,一切正常。但是当我的地图在另一个类中时,我无法做到这一点。
    • @GiuseppeCianci 在另一个班级,例如?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-31
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    相关资源
    最近更新 更多