使用mongoDB c#驱动程序将对象序列化为字符串值(就像在其上调用ToString())

时间:2014-06-06 21:30:59

标签: c# mongodb serialization bson

我正在使用MongoDB C#驱动程序。 我在C#中有一个数据结构

public class ResourceSpec
{
      public string TypeName
      {
          get;
          private set;
      }

      public HashSet<ResourceProperty> Properties
      {
          get;
          private set;
      }
}

public class ResourceProperty
{
     public string Val
     {
         get;
         private set;
     }
} 

我希望将其序列化为:

{TypeName: 'blabla', Properties: ['value1', 'value2', 'value3' ]}

而不是

{TypeName: 'blabla', Properties: [{Val: 'value1'}, {Val: ' value2'}, {Val: ' value3'}] }

我该怎么做?

1 个答案:

答案 0 :(得分:0)

您可以编写自定义序列化程序并将其注册到驱动程序。有一点需要注意,一旦注册了序列化程序,它将用于每个ResourceSpec实例。

public class ResourceSpecSerializer : BsonBaseSerializer
{
    public override object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)
    {
        // Deserialize logic
    }

    public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options)
    {
        // Serialize logic
    }

使用BsonSerializer.RegisterSerializer

注册
BsonSerializer.RegisterSerializer(typeof(ResourceSpec), new ResourceSpecSerializer());

为了实现自定义JSON,我建议调查Json.NET,特别是JsonWriter

以下是使用JsonWriter

的示例
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb); 

using(JsonWriter writer = new JsonTextWriter(sw))
{
    writer.Formatting = Formatting.Indented;

    writer.WriteStartObject();
    writer.WritePropertyName("CPU");
    writer.WriteValue("Intel");
    writer.WritePropertyName("PSU");
    writer.WriteValue("500W");
    writer.WritePropertyName("Drives");
    writer.WriteStartArray();
    writer.WriteValue("DVD read/writer");
    writer.WriteComment("(broken)");
    writer.WriteValue("500 gigabyte hard drive");
    writer.WriteValue("200 gigabype hard drive");
    writer.WriteEnd();
    writer.WriteEndObject();
}

将显示:

 {
    "CPU": "Intel",
    "PSU": "500W",
    "Drives": [
         "DVD read/writer"
         /*(broken)*/,
        "500 gigabyte hard drive",
        "200 gigabype hard drive"
     ]
 }