gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:17:08 24 4
gpt4 key购买 nike

我正在使用 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'}] }

我该怎么做?

最佳答案

您可以编写自定义序列化程序并将其注册到驱动程序。需要注意的一件事是,一旦您注册了序列化程序,它将用于每个 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"
]
}

关于c# - 使用 mongoDB c# 驱动程序将对象序列化为字符串值(就像在其上调用 ToString() 一样),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24090918/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com