2017-02-20 46 views
0

我有收集與成千上萬的文件,在文件有一個名爲領域,問題是目前其類型爲字符串,所以當它不可用,老開發人員將其設置爲「N/A」。現在我想在C#中將此字段的類型更改爲數字(在n/a時將其設置爲0),但如果我這樣做,則無法加載過去的數據。 我們可以自定義反序列化,以便將N/A轉換爲0嗎?定製反序列化

+2

人們爲什麼downvoted沒有對此有何評論?如果是這樣,我怎麼知道我的問題有什麼問題? – kvuong

回答

1

你需要創建一個IBsonSerializerSerializerBase<>並將其連接到您希望使用BsonSerializerAttribute序列化屬性。像下面這樣:

public class BsonStringNumericSerializer : SerializerBase<double> 
{ 
    public override double Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) 
    { 
     var type = context.Reader.GetCurrentBsonType(); 
     if (type == BsonType.String) 
     { 
      var s = context.Reader.ReadString(); 
      if (s.Equals("N/A", StringComparison.InvariantCultureIgnoreCase)) 
      { 
       return 0.0; 
      } 
      else 
      { 
       return double.Parse(s); 
      } 
     } 
     else if (type == BsonType.Double) 
     { 
      return context.Reader.ReadDouble(); 
     } 
     // Add any other types you need to handle 
     else 
     { 
      return 0.0; 
     } 
    } 
} 

public class YourClass 
{ 
    [BsonSerializer(typeof(BsonStringNumericSerializer))] 
    public double YourDouble { get; set; } 
} 

如果你不想使用屬性,你可以創建一個IBsonSerializationProvider和使用BsonSerializer.RegisterSerializationProvider註冊。

MongoDB的C#BSON序列化的完整文檔,可以發現here