【发布时间】:2017-06-19 15:35:01
【问题描述】:
更新到 jongo 1.3.0 后,从 MongoDB 读取文档时开始出现以下错误:
com.fasterxml.jackson.core.JsonGenerationException: BsonSerializer can only be used with BsonGenerator
经过一些测试我发现使用@JsonTypeInfo时出现问题,并且MongoDB文档包含
一个日期对象之前类型属性。给定:
@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' } }
这个(spock)测试会失败
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()]
请注意,如果 date 为 null 或在 type 之后,则测试通过。
我想更新 Jongo 和 Jackson 但我不能保证属性的顺序 在我们的数据库中。问题是能否解决问题。
- 我尝试将 Jackson 更新到 2.8.6 和 2.8.7,但没有区别。
- 当我尝试
de.undercouch:bson4jackson:2.8.0-SNAPSHOT时,解析的date将在type之后为空
类似的错误似乎已经用 2.8.0-SNAPSHOT 解决了:https://github.com/michel-kraemer/bson4jackson/issues/67
我在这里发布了一个问题:https://github.com/michel-kraemer/bson4jackson/issues/72
【问题讨论】:
-
您找到解决此问题的方法了吗?我们面临着完全相同的问题,使用 de.undercouch:bson4jackson:2.8.0-SNAPSHOT 并不能解决它。
标签: java mongodb jackson bson jongo