When updating to jongo 1.3.0 we started to get the following error when reading documents from MongoDB:
com.fasterxml.jackson.core.JsonGenerationException: BsonSerializer can only be used with BsonGenerator
After some testing I found that the problem occurs when using @JsonTypeInfo
and the MongoDB document contains
a date object before the type property. Given:
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.EXISTING_PROPERTY,
property = 'type',
visible = true)
@JsonSubTypes([
@JsonSubTypes.Type(name = 'a', value = A),
@JsonSubTypes.Type(name = 'b', value = B)
])
abstract class Base {
String string // For reference
Date date
String type
}
class A extends Base { A() { type = 'a' } }
class B extends Base { B() { type = 'b' } }
This (spock) test will fail
def mapper = new ObjectMapper(new BsonFactory()).registerModule(new BsonModule())
def bytes = mapper.writeValueAsBytes(original)
expect:
def parsed = mapper.readValue(bytes, Base)
parsed instanceof A // com.fasterxml.jackson.core.JsonGenerationException: BsonSerializer can only be used with BsonGenerator
parsed.string == original.string
parsed.date == original.date // parsed.date is null with 'de.undercouch:bson4jackson:2.8.0-SNAPSHOT'
parsed.type == original.type
where:
testCase | original
'A' | new A(string: 'string', date: new Date(), type: 'a') // fails
'String, Date, Type' | [string: 'string', date: new Date(), type: 'a'] // fails
'String, null date, Type' | [string: 'string', date: null, type: 'a']
'String, Type, Date' | [string: 'string', type: 'a', date: new Date()]
'Type, String, Date' | [type: 'a', string: 'string', date: new Date()]
Note that if date
is null or comes after type
the test passes.
I would like to update Jongo and Jackson but don't think I can guarantie the order of properties on our DB. Question is if the issue can be solved.
- I've tried updating Jackson to 2.8.6 and 2.8.7 but no difference.
- When I try
de.undercouch:bson4jackson:2.8.0-SNAPSHOT
the parseddate
will be null if it comes aftertype
A similar bug seems to have been solved with 2.8.0-SNAPSHOT: https://github.com/michel-kraemer/bson4jackson/issues/67
I've posted an issue here: https://github.com/michel-kraemer/bson4jackson/issues/72