【发布时间】:2015-02-01 17:02:31
【问题描述】:
我有以下课程
public class BetWrapper {
private String description;
private Calendar startTime;
private HashMap<String, SimpleEntry<Integer, Double>> map;
public BetWrapper() {
map = new HashMap<>();
}
public Calendar getStartTime() {
return startTime;
}
public void setStartTime(Calendar startTime) {
this.startTime = startTime;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public HashMap<String, SimpleEntry<Integer, Double>> getMap() {
return map;
}
public void setMap(HashMap<String, SimpleEntry<Integer, Double>> map) {
this.map = map;
}
}
我正在使用 JSONUtil 类
public class JSONUtil {
private JSONUtil() {}
public static <T> T fromJSON(String content, Class<T> clazz) throws TechnicalException {
try {
return new ObjectMapper().readValue(content, clazz);
} catch (IOException e) {
throw new TechnicalException(e);
}
}
public static String toJSON(Object obj) throws TechnicalException {
try {
return new ObjectMapper().writeValueAsString(obj);
} catch (JsonProcessingException ex) {
throw new TechnicalException(ex);
}
}
}
我想将 JSON 反序列化为 BetWrapper 对象。但是下面的代码会产生一些异常。
BetWrapper betWrapper = new BetWrapper();
betWrapper.setDescription("Stoke City - Arsenal");
betWrapper.setStartTime(Calendar.getInstance());
HashMap<String, AbstractMap.SimpleEntry<Integer, Double>> map = new HashMap<>();
map.put("home_team", new AbstractMap.SimpleEntry<>(1, 2.85));
betWrapper.setMap(map);
String json = JSONUtil.toJSON(betWrapper);
JSONUtil.fromJSON(json, BetWrapper.class);
例外情况是:
Caused by: com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class java.util.AbstractMap$SimpleEntry<java.lang.Integer,java.lang.Double>]: can not instantiate from JSON object (need to add/enable type information?)
at [Source: {"description":"Stoke City - Arsenal","startTime":1417648132139,"map":{"home_team":"key":1,"value":2.85}}}; line: 1, column: 85] (through reference chain: by.bsu.kolodyuk.bettingapp.model.entity.BetWrapper["map"])
如何正确反序列化?似乎问题在于 SimpleEntry 中的类型 K,V 应该以某种方式为 Jackson 指定。
有什么想法吗?
【问题讨论】:
-
我们来看看
SimpleEntry。 -
SimpleEntry 是 AbstractMap 的静态内部类
标签: java json generics jackson