gpt4 book ai didi

json - Jackson 正在向 POJO 添加冗余数据,然后无法将其读回

转载 作者:行者123 更新时间:2023-12-01 01:30:07 26 4
gpt4 key购买 nike

我正在使用 Jackson 以在客户端和服务器之间发送 JSON 类型的数据。
我正在尝试使用 Jackson 的完整绑定(bind)功能,并将其应用于标准 POJO。
问题是 jackson 似乎在服务器上编码期间添加了冗余数据,所以当我尝试将其解码回客户端的 POJO 时,我遇到了错误。

这是 jackson 弦乐的摘录:

{"_class":"com.mycoomp.MyObject","_id":{"time":1300314145000,"new":false,"machine":1652794940,"inc":-510750341},"language":"",“类型”.....

MyObject 包含“语言”和“类型”,但它不包含不属于它的“时间”、"new"和“机器”,但在客户端我收到此错误:

无法识别的字段“时间”(类 org.bson.types.ObjectId),在 [来源:java.io.StringReader@1c56c60;未标记为可忽略;行:1,列:102](通过引用链:com.mycomp.MyObject["_id"]->org.bson.types.ObjectId["time"])

有任何想法吗...?

最佳答案

解决方案是为 ObjectId 提供一个自定义的序列化器/反序列化器:

public class ObjectIdMapping {
public static class ObjectIdSerializer extends JsonSerializer<ObjectId>{
@Override
public void serialize(ObjectId id, JsonGenerator json,
SerializerProvider provider) throws IOException,
JsonProcessingException {
json.writeString(id.toString());

}
}
public static class ObjectIdDeerializer extends JsonDeserializer<ObjectId>{
@Override
public ObjectId deserialize(JsonParser jp, DeserializationContext context)
throws IOException, JsonProcessingException {
if (!ObjectId.isValid(jp.getText())) throw context.mappingException("invalid ObjectId " + jp.getText());
return new ObjectId(jp.getText());
}
}
}

并将它们注册为 the documentation 中描述的任何方法.例如,添加您的 POJO:
@JsonSerialize(using = ObjectIdMapping.ObjectIdSerializer.class)
@JsonDeserialize(using = ObjectIdMapping.ObjectIdDeerializer.class)
public ObjectId od;

关于json - Jackson 正在向 POJO 添加冗余数据,然后无法将其读回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5332666/

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