下面是我们如何解决这个问题(最终的结果是龙目岛,杰克逊和MongoDB之间的超光滑):
提供者:
public class JacksonCodecProvider implements CodecProvider {
private final ObjectMapper objectMapper;
public JacksonCodecProvider(final ObjectMapper bsonObjectMapper) {
this.objectMapper = bsonObjectMapper;
}
@Override
public <T> Codec<T> get(final Class<T> type, final CodecRegistry registry) {
return new JacksonCodec<>(objectMapper, registry, type);
}
}
以及编解码器本身:
class JacksonCodec<T> implements Codec<T> {
private final ObjectMapper objectMapper;
private final Codec<RawBsonDocument> rawBsonDocumentCodec;
private final Class<T> type;
public JacksonCodec(ObjectMapper objectMapper,
CodecRegistry codecRegistry,
Class<T> type) {
this.objectMapper = objectMapper;
this.rawBsonDocumentCodec = codecRegistry.get(RawBsonDocument.class);
this.type = type;
}
@Override
public T decode(BsonReader reader, DecoderContext decoderContext) {
try {
RawBsonDocument document = rawBsonDocumentCodec.decode(reader, decoderContext);
String json = document.toJson();
return objectMapper.readValue(json, type);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public void encode(BsonWriter writer, Object value, EncoderContext encoderContext) {
try {
String json = objectMapper.writeValueAsString(value);
rawBsonDocumentCodec.encode(writer, RawBsonDocument.parse(json), encoderContext);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public Class<T> getEncoderClass() {
return this.type;
}
}
当合并与龙目岛和最新的杰克逊注解,它允许我们做这样的东西(几乎看起来像Java代码,呃?):
@JsonIgnoreProperties(ignoreUnknown=true)
@JsonDeserialize(builder = Account.AccountBuilder.class)
@Builder(toBuilder=true)
@Value
public class Account {
@JsonProperty private String _id;
@JsonProperty private long _version;
@JsonProperty private String organizationName;
@JsonPOJOBuilder(withPrefix = "")
public static final class AccountBuilder {
}
}
然后:
Account account = collection.find(eq("_id", id)).first();
System.out.println(account.getOrganizationName());
我不知道是什么做的编解码器,但你有没有看春节数据映射器? – chrylis
我确实,但这不是我所需要的。新的mongo java驱动程序(版本3+)使我们有机会通过编解码器直接解析响应,而无需使用中间表示(DBObject)。但是你必须自己写(http://mongodb.github.io/mongo-java-driver/3.0/bson/codecs/)。我正在寻找一些自动编写这些编解码器的库,所以我不必手动执行。 – caeus