我想通过使用默认的编解码器注册表(MongoClient.getDefaultCodecRegistry())和PojoCodecProvider提供的构建器从mongo数据库加载类“DataTable”的实例。我在编解码器提供程序中注册了DataTable类,当records字段为null时,该对象从数据库中正确映射。然而,当records属性包含数据时,我收到错误。此外,我需要将记录字段定义为具有任意属性的对象列表。是否可以为此目的使用默认的PojoCodecProvider?还有其他选择吗?
import com.mongodb.BasicDBList;
import org.bson.types.ObjectId;
import java.util.List;
public class DataTable {
private ObjectId id;
private List<String> fields;
private BasicDBList records;
public ObjectId getId() {
return id;
}
public void setId(ObjectId id) {
this.id = id;
}
public List<String> getFields() {
return fields;
}
public void setFields(List<String> fields) {
this.fields = fields;
}
public BasicDBList getRecords() {
return records;
}
public void setRecords(BasicDBList records) {
this.records = records;
}
}
加载DataTable类的实例时得到的异常如下。
2018-03-21T16:32:04,526 [http-bio-8081-exec-4] ERROR ...service.controllers.BaseController - Failed to decode 'records'. Unable to set value for property 'records' in DataTable
org.bson.codecs.configuration.CodecConfigurationException: Failed to decode 'records'. Unable to set value for property 'records' in DataTable
at org.bson.codecs.pojo.PojoCodecImpl.decodePropertyModel(PojoCodecImpl.java:192) ~[bson-3.6.3.jar:?]
at org.bson.codecs.pojo.PojoCodecImpl.decodeProperties(PojoCodecImpl.java:168) ~[bson-3.6.3.jar:?]
at org.bson.codecs.pojo.PojoCodecImpl.decode(PojoCodecImpl.java:122) ~[bson-3.6.3.jar:?]
at org.bson.codecs.pojo.PojoCodecImpl.decode(PojoCodecImpl.java:126) ~[bson-3.6.3.jar:?]
当我尝试使用以下代码加载项目
时,我收到此异常DataTable item = collection.find(eq(new ObjectId(id))).first();
答案 0 :(得分:0)
嗯,你可以使用的另一个选择是杰克逊序列化。 我觉得这样的事情很适合你
Document document = collection
.find(eq(new ObjectId(id)))
.first();
String json = document.toJson();
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
DataTable dataTable = mapper.readValue(json, DataTable.class);