kmongo
kmongo copied to clipboard
Provide Jackson built-in Serializer & Deserializer classes for Mongo Geometry classes
I am getting com.fasterxml.jackson.databind.JsonMappingException: Cannot deserialize Class MainKt$main$PointTest (of type local/anonymous) as a Bean when using a Mongo Point class with the Jackson client.
Here is some code to reproduce the error
import com.fasterxml.jackson.databind.JsonMappingException
import com.mongodb.client.model.geojson.Point
import com.mongodb.client.model.geojson.Position
import org.litote.kmongo.KMongo
import org.litote.kmongo.getCollection
fun main() {
data class PointTest(val location: Point)
val client = KMongo.createClient() //get com.mongodb.MongoClient new instance
val database = client.getDatabase("test") //normal java driver usage
val col = database.getCollection<PointTest>() //KMongo extension method
col.insertOne(PointTest(Point(Position(20.0, 20.0))))
try {
col.find().toList()
} catch (e: JsonMappingException) {
e.printStackTrace()
}
}
This is because com.mongodb.client.model.geojson.Point has no Jackson serializer nor deserializer. The stacktrace is clear:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of com.mongodb.client.model.geojson.Point (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
You have two options:
- use kmongo-native: it will work out of the box (as a Codec is provided by default for Geometry classes)
- Add a Jackson serializer and deserializer for Geometry classes (based on Codec implementation). Please fill a PR!
@zigzago I included both kmongo-native and kmongo-native-mapping deps, however I still ran into the same issue using KMongo.createClient(). I'm wondering if I missed something obvious here?
@channguyen please provide a test case. You can see a simple test case here: https://github.com/Litote/kmongo/commit/a55b2b3dd2e9495fccad7c24a3d07380caa43b19
Hello @zigzago, I tried to execute your sample test case and it doesn't pass. I have the following Kmong deps in my project:
implementation("org.litote.kmongo:kmongo:4.1.3")
implementation("org.litote.kmongo:kmongo-id:4.1.3")
implementation("org.litote.kmongo:kmongo-native:4.1.3")
The error I get is:
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.mongodb.client.model.geojson.Point` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
at [Source: de.undercouch.bson4jackson.io.LittleEndianInputStream@188cbcde; pos: 31] (through reference chain: com.octawizard.repository.reservation.Issue111MongoPoint$MyData["location"])
Is there any workaround for this?
@octawizard Remove the kmongo dependency (jackson mapping) - just keep the kmongo-native dependency
thank you @zigzago !