Serialize the object as a string value (as if it would call ToString () on it) using the mongoDB C # driver

I am using the MongoDB C # driver. I have a data structure in 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 to:

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

Instead

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

How can i do this?

+4
source share
1 answer

You can write your own serializer and register it using the driver. It should be noted that after registering your serializer, it will be used for each 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(typeof(ResourceSpec), new ResourceSpecSerializer());

To implement custom JSON, I suggest looking Json.NETand specificallyJsonWriter

Here is a usage example 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"
     ]
 }
0

Source: https://habr.com/ru/post/1543627/


All Articles