问题描述
我们需要从遗留服务器处理一些损坏的JSON,错误地将 null
值编码为文字null
输出中的字符串。
We need to process some broken JSON from a legacy server here that wrongly encodes null
values as literal "null"
strings in its output.
我已经发现我可能想要覆盖来修复这个,但这似乎在杰克逊内部如此深刻,我宁愿采取不同的方式。是否有替代方法,例如使用 ObjectMapper
为 String.class
添加自定义反序列化器,或者我丢失了?
I already found that I probably want to override https://github.com/FasterXML/jackson-core/blob/master/src/main/java/com/fasterxml/jackson/core/base/ParserMinimalBase.java#L368 to "fix" this, but this seems to be so deep inside Jackson that I'd rather do it differently. Are there alternatives, for example by using the ObjectMapper
to add a custom deserializer for the String.class
or am I lost?
推荐答案
好的,它通过覆盖标准字符串反序列化器来工作。不幸的是我不得不复制完整的实现,因为 org / codehaus / jackson / map / deser / std / StringDeserializer.java
是最终的,无法扩展。
Ok, it worked by overriding the standard String deserializer. Unfortunately I had to copy the complete implementation over because org/codehaus/jackson/map/deser/std/StringDeserializer.java
is final and cannot be extended.
public class FixesModule extends SimpleModule {
public FixesModule() {
super();
addDeserializer(String.class, new CustomStringDeserializer());
}
}
和
public class CustomStringDeserializer extends StdScalarDeserializer {
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);
}
}
这篇关于杰克逊:覆盖原始类型的反序列化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!