在使用自定义Map<Object, Object>
将Set<Map.Entry<Object, Object>>
映射到public class Test {
private static class Person {
@JsonProperty
String name;
@JsonProperty
String sex;
public Person(final String name, final String sex) {
this.name = name;
this.sex = sex;
}
}
@JsonProperty
Map<Person, Integer> map = Map.of(new Person("male", "m"), 42, new Person("female", "f"), 43);
}
时,反之亦然,Jackson仍然尝试查找Map密钥反序列化器:
线程“ main”中的异常com.fasterxml.jackson.databind.exc.InvalidDefinitionException:找不到类型[简单类型,类Test $ Person]的(映射)键反序列化器
这是我正在使用的POJO(仅出于c的演示目的):
public class Test {
public static final class Serialize extends StdConverter<Map<Object, Object>, Set<Map<String, Object>>> {
@Override
public Set<Map<String, Object>> convert(final Map<Object, Object> value) {
return value.entrySet().stream().map(e -> Map.of("key", e.getKey(), "value", e.getValue())).collect(toSet());
}
}
public static final class Deserialize extends StdConverter<Set<Map<String, Object>>, Map<Object, Object>> {
@Override
public Map<Object, Object> convert(final Set<Map<String, Object>> value) {
final Map<Object, Object> result = new LinkedHashMap<>();
for (final Map<String, Object> entry : value) {
result.put(entry.get("key"), entry.get("value"));
}
return result;
}
}
private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
static {
OBJECT_MAPPER.setConfig(OBJECT_MAPPER.getSerializationConfig().withInsertedAnnotationIntrospector(new NopAnnotationIntrospector() {
@Override
public Object findSerializationConverter(final Annotated a) {
if (a.getRawType() == Map.class) {
return new Serialize();
}
return super.findSerializationConverter(a);
}
@Override
public Object findDeserializationConverter(final Annotated a) {
if (a.getRawType() == Map.class) {
return new Deserialize();
}
return super.findDeserializationConverter(a);
}
}));
}
public static void main(final String[] args) throws IOException {
final Test test = new Test();
final String json = OBJECT_MAPPER.writeValueAsString(test);
System.err.println(json);
System.err.println(OBJECT_MAPPER.readValue(json, Test.class));
}
}
这是程序的其余部分,包括转换器:
dateFns.isToday(new Date());
为什么我仍然得到
线程“ main”中的异常com.fasterxml.jackson.databind.exc.InvalidDefinitionException:找不到类型[简单类型,类Test $ Person]的(映射)键反序列化器
我期望的是JSON输出:
{"map":[{"key":{"name":"female","sex":"f"},"value":43},{"key":{"name":"male","sex":"m"},"value":42}]}