杰克逊:覆盖原始类型的反序列化?

时间:2013-06-11 09:51:31

标签: java json jackson

我们需要处理来自旧服务器的一些损坏的JSON,这些JSON在其输出中错误地将null值编码为文字"null"字符串。

我已经发现我可能想要覆盖https://github.com/FasterXML/jackson-core/blob/master/src/main/java/com/fasterxml/jackson/core/base/ParserMinimalBase.java#L368以“修复”这个,但这似乎在杰克逊内部如此深刻,我宁愿采取不同的方式。是否有替代方案,例如使用ObjectMapperString.class添加自定义反序列化器或者我丢失了?

1 个答案:

答案 0 :(得分:2)

好的,它可以通过覆盖标准的String反序列化器来实现。不幸的是,我不得不复制完整的实现,因为org/codehaus/jackson/map/deser/std/StringDeserializer.java是最终的,无法扩展。

public class FixesModule extends SimpleModule {

    public FixesModule() {
        super();
        addDeserializer(String.class, new CustomStringDeserializer());
    }
}

public class CustomStringDeserializer extends StdScalarDeserializer<String> {

    private static final String NULL_STRING = "null";

    public CustomStringDeserializer() {
        super(String.class);
    }

    @Override
    public String deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        JsonToken curr = jp.getCurrentToken();
        // Usually should just get string value:
        if (curr == JsonToken.VALUE_STRING) {
            // BEGIN NULL_STRING fix
            if (NULL_STRING.equals(jp.getText())) {
                return null;
            }
            // END NULL_STRING fix
            return jp.getText();
        }
        // [JACKSON-330]: need to gracefully handle byte[] data, as base64
        if (curr == JsonToken.VALUE_EMBEDDED_OBJECT) {
            Object ob = jp.getEmbeddedObject();
            if (ob == null) {
                return null;
            }
            if (ob instanceof byte[]) {
                return Base64Variants.getDefaultVariant().encode((byte[]) ob, false);
            }
            // otherwise, try conversion using toString()...
            return ob.toString();
        }
        // Can deserialize any scalar value, but not markers
        if (curr.isScalarValue()) {
            return jp.getText();
        }
        throw ctxt.mappingException(_valueClass, curr);
    }

    // 1.6: since we can never have type info ("natural type"; String, Boolean,
    // Integer, Double):
    // (is it an error to even call this version?)
    @Override
    public String deserializeWithType(JsonParser jp, DeserializationContext ctxt, TypeDeserializer typeDeserializer)
            throws IOException, JsonProcessingException {
        return deserialize(jp, ctxt);
    }
}