描述:5c738ea8a28b504c04ae44ed来自于mongodb的_id字段,按理只是将string类型的ObjectId转换回ObjectId类型应该不会出错。
报错:java.lang.IllegalArgumentException: invalid hexadecimal representation of an ObjectId: ["5c738ea8a28b504c04ae44ed"]
解决办法:将ObjectId序列化一下
@JsonComponent
public class ObjectIdCombinedSerializer {
public static class ObjectIdJsonSerializer extends JsonSerializer<ObjectId> {
@Override
public void serialize(ObjectId objectId, JsonGenerator jsonGenerator,
SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeString(objectId.toString());
}
}
public static class ObjectIdJsonDeserializer extends JsonDeserializer<ObjectId> {
@Override
public ObjectId deserialize(JsonParser parser, DeserializationContext deserializationContext)
throws IOException {
var node = (JsonNode)parser.getCodec().readTree(parser);
return new ObjectId(node.asText());
}
}
}