2016-08-14 38 views
0

如果我使用從MongoDB的公報階驅動程序的「本地」 JSON支持:MongoDB的斯卡拉驅動程序自定義轉換成JSON

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

它產生的JSON文本類型的前綴擴展類型:

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

我想避免這種類型轉換,並直接寫入每種類型的值。有可能以某種方式覆蓋某種類型的編碼行爲嗎?

回答

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(); 
    }