Mongodb scala驱动程序自定义转换为JSON

时间:2016-08-14 19:53:26

标签: mongodb mongodb-java

如果我使用来自mongodb oficial scala驱动程序的“本机”json支持:

val jsonText = Document(...).toJson()

它生成带有扩展类型前缀类型的json文本:

{ "$oid" : "AABBb...." }   - for ObjectID, 
{ "$longNumber" : 123123  } - for Long and etc.

我想避免这种类型转换,并直接只为每种类型写入值。是否有可能以某种方式覆盖某些类型的编码行为?

1 个答案:

答案 0 :(得分:0)

您可以继承JsonWriter并覆盖writeXXX方法。例如,要自定义日期序列化,您可以使用:

class CustomJsonWriter extends JsonWriter {
    public CustomJsonWriter(Writer writer) {
        super(writer);
    } 

    public CustomJsonWriter(Writer writer, JsonWriterSettings settings) {
        super(writer, settings);
    }

    @Override
    protected void doWriteDateTime(long value) {
        doWriteString(DateTimeFormatter.ISO_DATE_TIME
            .withZone(ZoneId.of("Z"))
            .format(Instant.ofEpochMilli(value)));
    }
}

然后您可以使用被覆盖的版本:

    public static String toJson(Document doc) {
        CustomJsonWriter writer = new CustomJsonWriter(new StringWriter(), new JsonWriterSettings());
        DocumentCodec encoder = new DocumentCodec();
        encoder.encode(writer, doc, EncoderContext.builder().isEncodingCollectibleDocument(true).build());
        return writer.getWriter().toString();
    }