JsonMappingException:未实现类型id处理,带有enableDefaultTyping和自定义序列化程序

时间:2019-07-10 12:46:06

标签: java jackson jackson-databind

我使用Java 9,Jackson-core和jackson-databind 2.5.5 我想将带有DefaultTyping.NON_FINAL选项的自定义序列化用于在Json中编写类名称。

如果我删除默认键入NON_FINAL,则一切正常。

当我添加NON_FINAL选项时,将调用我的自定义序列化程序“ MySerializer”,但我有异常JsonMappingException:未实现类型ID处理

public class Main {
    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.enableDefaultTyping();
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);

        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(new MySerializer());

        objectMapper.registerModule(simpleModule);

        System.out.println(objectMapper.writeValueAsString(new MyObject(1)));
    }
}

public class MyObject {
    private int a = 0;

    public MyObject() {
    }

    public MyObject(int a) {
        this.a = a;
    }

    public int getA() {
        return a;
    }

    public void setA(int a) {
        this.a = a;
    }
}

public class MySerializer extends StdSerializer<MyObject> {
    protected MySerializer() {
        super(MyObject.class);
    }

    public void serialize(MyObject myObject, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeStartObject();
        jsonGenerator.writeNumberField("newNameForFieldA", myObject.getA());
        jsonGenerator.writeEndObject();
    }
}


    <dependencies>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.5.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.5.5</version>
        </dependency>
    </dependencies>

没有NON_FINAL默认类型的结果:

{“ newNameForFieldA”:1}

例外:

线程“ main”中的异常com.fasterxml.jackson.databind.JsonMappingException:未为com.test.jackson.main2.MyObject类型实现类型ID处理(由com.test.jackson.main2.MySerializer类型的序列化器实现)     在com.fasterxml.jackson.databind.SerializerProvider.mappingException(SerializerProvider.java:1047)     在com.fasterxml.jackson.databind.JsonSerializer.serializeWithType(JsonSerializer.java:142)     在com.fasterxml.jackson.databind.ser.impl.TypeWrappedSerializer.serialize(TypeWrappedSerializer.java:32)     在com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:129)     在com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3387)     在com.fasterxml.jackson.databind.ObjectMapper.writeValueAsString(ObjectMapper.java:2781)     在com.test.jackson.main2.Main.main(Main.java:18)

1 个答案:

答案 0 :(得分:1)

启用DefaultTyping.NON_FINAL时,如果定义了自定义序列化程序,objectMapper将使用在“ JsonSerializer”类中定义的“ serializeWithType”方法来进行序列化工作。

因此,要解决此问题,您需要覆盖方法“ serializeWithType”。