0

我目前正在尝试使用 Jackson 2.8.4 将自定义 Map 类型序列化和反序列化为 JSON。我已经设法根据这个答案进行序列化,但我在反序列化方面苦苦挣扎。这是一个例子:

public class TestMapSerialize {

    public interface TestMapGetters {
        Map<String, String> getFooMap();
        Map<String, String> getBarMap();
    }

    @JsonSerialize(as = TestMapGetters.class)
    public static class TestMap extends ForwardingMap<String, String>
            implements TestMapGetters {

        private Map<String, String> fooMap;
        private Map<String, String> barMap;

        @Override
        protected Map<String, String> delegate() {
            return ImmutableMap.<String, String>builder()
                    .putAll(fooMap)
                    .putAll(barMap)
                    .build();
        }

        // Getters and setters...

    }

    public static void main(String[] args) throws IOException {
        final ObjectMapper mapper = new ObjectMapper();
        final TestMap map = new TestMap();

        map.setFooMap(ImmutableMap.of("a", "b", "c", "d"));
        map.setBarMap(ImmutableMap.of("e", "f", "g", "h"));

        final String json = mapper.writeValueAsString(map);

        // Prints {"fooMap":{"a":"b","c":"d"},"barMap":{"e":"f","g":"h"}} as expected.
        System.out.println(json);

        // Throws JsonMappingException, see below.
        final TestMap copy = mapper.readValue(json, TestMap.class);
    }

}

当我尝试如上所述反序列化时,出现异常:

Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.lang.String out of START_OBJECT token
 at [Source: {"fooMap":{"a":"b","c":"d"},"barMap":{"e":"f","g":"h"}}; line: 1, column: 11] (through reference chain: test.TestMapSerialize$TestMap["fooMap"])
    at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:270)
    at com.fasterxml.jackson.databind.DeserializationContext.reportMappingException(DeserializationContext.java:1234)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1122)
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1075)
    at com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:60)
    at com.fasterxml.jackson.databind.deser.std.StringDeserializer.deserialize(StringDeserializer.java:11)
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer._readAndBindStringKeyMap(MapDeserializer.java:517)
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:362)
    at com.fasterxml.jackson.databind.deser.std.MapDeserializer.deserialize(MapDeserializer.java:27)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3798)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2842)
    at test.TestMapSerialize.main(TestMapSerialize.java:66)

所以杰克逊仍然试图将我的课程反序列化,就好像它是一个通用的Map,因为它是一个 bean,所以它不起作用。我也尝试过添加@JsonDeserialize(as = TestMapGetters.class),但后来我得到:

Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Failed to narrow type [map type; class test.TestMapSerialize$TestMap, [simple type, class java.lang.String] -> [simple type, class java.lang.String]] with annotation (value test.TestMapSerialize$TestMapGetters), from 'test.TestMapSerialize$TestMap': Class test.TestMapSerialize$TestMapGetters not subtype of [map type; class test.TestMapSerialize$TestMap, [simple type, class java.lang.String] -> [simple type, class java.lang.String]]
    at com.fasterxml.jackson.databind.AnnotationIntrospector.refineDeserializationType(AnnotationIntrospector.java:1194)
    at com.fasterxml.jackson.databind.deser.DeserializerCache.modifyTypeByAnnotation(DeserializerCache.java:519)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer(DeserializerCache.java:333)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:264)
    at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCacheValueDeserializer(DeserializerCache.java:244)
    at com.fasterxml.jackson.databind.deser.DeserializerCache.findValueDeserializer(DeserializerCache.java:142)
    at com.fasterxml.jackson.databind.DeserializationContext.findRootValueDeserializer(DeserializationContext.java:476)
    at com.fasterxml.jackson.databind.ObjectMapper._findRootDeserializer(ObjectMapper.java:3899)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3794)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2842)
    at test.TestMapSerialize.main(TestMapSerialize.java:68)
Caused by: java.lang.IllegalArgumentException: Class test.TestMapSerialize$TestMapGetters not subtype of [map type; class test.TestMapSerialize$TestMap, [simple type, class java.lang.String] -> [simple type, class java.lang.String]]
    at com.fasterxml.jackson.databind.type.TypeFactory.constructSpecializedType(TypeFactory.java:359)
    at com.fasterxml.jackson.databind.AnnotationIntrospector.refineDeserializationType(AnnotationIntrospector.java:1192)
    ... 10 more

这是有道理的,因为它不是子类型。我宁愿不必编写自定义反序列化器,因为如果我的对象不是Map. 有什么办法可以告诉杰克逊忽略我的课程是 aMap并且只是反序列化为 bean 的事实吗?

4

1 回答 1

0

我发现我可以在我的TestMap类中添加一个静态创建者方法:

@JsonCreator
static TestMap fromJson(
        @JsonProperty("fooMap") ImmutableMap<String, String> fooMap,
        @JsonProperty("barMap") ImmutableMap<String, String> barMap) {
    final TestMap map = new TestMap();
    map.setFooMap(fooMap);
    map.setBarMap(barMap);
    return map;
}

有一种方式说“只是将序列化和反序列化为 POJO”以避免整体@JsonCreator@JsonSerialize(as)冗长的问题仍然会很好。

于 2016-10-20T19:43:57.030 回答