- 杰克逊地图<字符串,对象>实施
问题描述:
的系列化我有以下类:- 杰克逊地图<字符串,对象>实施
public class Some implements Map<String, Object>{
private Map<String, Object> innerMap;
//implementation that can only set innerMap in constructor and cannot add or remove values
}
的问题是,我不能在杰克逊正确反序列化这一点。如果我序列无默认输入,这是确定的,因为它被序列化为{“一”:“二”},正确地反序列化(我不得不实施解串器
return new Some(jp.readValueAs(new TypeReference<HashMap<String,Object>>(){}));
当我使用默认的打字开启,这个序列化为
["com.class.Some",{"one":"two"}]
但反序列化抛出
com.fasterxml.jackson.databind.JsonMappingException: Unexpected token (START_OBJECT), expected START_ARRAY: need JSON Array to contain As.WRAPPER_ARRAY type information for class java.util.HashMap
有什么想法?
答
这正是我需要的 - 自定义解串器:
public class SomeDeserializer extends JsonDeserializer<Some> {
@Override
public Object deserializeWithType(JsonParser jsonParser, DeserializationContext ctxt, TypeDeserializer typeDeserializer) throws IOException {
return typeDeserializer.deserializeTypedFromObject(jsonParser, ctxt);
}
@SuppressWarnings("unchecked")
@Override
public Some deserialize(JsonParser jp, DeserializationContext ctxt)
throws IOException {
JsonDeserializer<Object> deserializer = ctxt.findRootValueDeserializer(
ctxt.getTypeFactory().constructMapType(Map.class, String.class, Object.class));
return new Some((Map) deserializer.deserialize(jp, ctxt, new HashMap<>()));
}
}
答
注释你的构造与@JsonCreator
:
public static void main(String[] args) throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
Some some = new Some(new HashMap<String, Object>() {{put("a", 1);}});
String json = mapper.writeValueAsString(some);
System.out.println("serialized : " + json);
some = mapper.readValue(json, Some.class);
System.out.println("deserialized: " + some);
}
// Read only delegating Map
public static class Some extends AbstractMap<String, Object> {
private Map<String, Object> delegate;
@JsonCreator
public Some(Map<String, Object> delegate) {
this.delegate = Collections.unmodifiableMap(delegate);
}
@Override
public Set<Entry<String, Object>> entrySet() {
return delegate.entrySet();
}
}
我这里的问题是,有些实现了Map接口,并具有@Override 公共对象认沽(字符串键,对象值){ throw new UnsupportedOperationException(“Is Immutable”); }所以你的代码我得到这个异常。 – bojanv55
示例中的映射是不可变的,并且在调用'put'时抛出'UnsupportedOperationException'。 – teppic