【问题标题】:Date and 'polymorphic' class causes JsonGenerationException: BsonSerializer can only be used with BsonGenerator日期和“多态”类导致 JsonGenerationException:BsonSerializer 只能与 BsonGenerator 一起使用
【发布时间】: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


【解决方案1】:

确保排序不是必需的,因为内容将根据需要进行缓冲。但是,这确实引发了一个问题,因为虽然 TokenBuffer 实现了基本 JsonGenerator,但它没有(也不能)实现 BSON 特定的子类型。

但我认为除了将jackson-databindjackson-core 升级到2.8.6(这是有道理的;修复是在2.8.3 左右)之外,您还需要更新版本的bson4jackson。但是看起来还没有发布 2.8,只有 2.7。 需要就您提到的要求发布的问题添加注释。

【讨论】:

  • 我试过de.undercouch:bson4jackson:2.8.0-SNAPSHOT但遇到了一个新问题,更新了问题
  • @Love 你最好的选择可能是向bson4jackson 提交问题以解决剩余问题。
  • 是的,我已经做到了here。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 2018-09-06
  • 1970-01-01
  • 2020-01-31
  • 2012-05-26
  • 2016-03-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多