Search code examples
mongodbmongodb-java

Failed to decode property of type BasicDBList with PojoCodecProvider in mongo db


I am tying to load an instance of the class "DataTable" from a mongo database by using the default codec registry (MongoClient.getDefaultCodecRegistry()) and the builder provided by the PojoCodecProvider. I have registered the DataTable class in the codec provider and the object is properly mapped from the database when the records field is null. Nevertheless, I get an error when the records property contains data. Furthermore, I need to have the records field defined as a list of objects with arbitrary attributes. Is it possible to use the default PojoCodecProvider for this purpose? Is there any other alternative?

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;
    }
}

The exception that I get when load an instance of the DataTable class is the following.

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:?]

I get this exception when I try to load an item with the following code

DataTable item = collection.find(eq(new ObjectId(id))).first();

Solution

  • Well, one alternative you can use is Jackson Serialization. I think something like this would suit you just fine

        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);
    

    See this question converting Document objects in MongoDB 3 to POJOS for reference