简体   繁体   English

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

[英]Serialize object as string value (as if calling ToString() on it) with mongoDB c# driver

I am using MongoDB C# driver. 我正在使用MongoDB C#驱动程序。 I have a datastructure in 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;
     }
} 

I want it to be serialized into: 我希望它被序列化为:

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

Instead of 代替

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

How can I do that? 我怎样才能做到这一点?

You can write a custom serializer and register it with the driver. 您可以编写自定义序列化程序并将其注册到驱动程序。 One thing to note that once you register your serializer it will be used for every ResourceSpec instance. 有一点需要注意,一旦注册了序列化程序,它将用于每个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
    }

And register it using BsonSerializer.RegisterSerializer 并使用BsonSerializer.RegisterSerializer注册它

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

For implementing the custom JSON, i suggest looking into Json.NET and specificly JsonWriter 为了实现自定义JSON,我建议查看Json.NET ,特别是JsonWriter

Here is an example of using 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();
}

Will display: 将显示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM