gpt4 book ai didi

java - Jackson:覆盖原始类型反序列化?

转载 作者:搜寻专家 更新时间:2023-10-31 20:29:03 25 4
gpt4 key购买 nike

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

我已经发现我可能想要覆盖 https://github.com/FasterXML/jackson-core/blob/master/src/main/java/com/fasterxml/jackson/core/base/ParserMinimalBase.java#L368 “修复”这个问题,但这似乎深深 Root 于 Jackson 的内心深处,我宁愿以不同的方式来做。是否有替代方案,例如使用 ObjectMapperString.class 添加自定义反序列化器,或者我迷路了吗?

最佳答案

好的,它通过覆盖标准的字符串反序列化器来工作。不幸的是,我不得不复制完整的实现,因为 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);
}
}

关于java - Jackson:覆盖原始类型反序列化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17041249/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com