字典<字符串、对象>序列化
本文关键字:序列化 对象 字符串 字典 | 更新日期: 2023-09-27 18:32:12
>我的数据类包含一些高度多样化的数据的字典字段。
internal class Program
{
public class DTO
{
public string Name { get; set; }
public Dictionary<string, object> Data { get; set; }
}
static void Main(string[] args)
{
var dictSerializer = new DictionaryInterfaceImplementerSerializer<Dictionary<string, object>>(DictionaryRepresentation.Document);
BsonClassMap.RegisterClassMap<DTO>(cm => cm.MapMember(dto => dto.Data).SetSerializer(dictSerializer));
var instance = new DTO
{
Name = "test",
Data = new Dictionary<string, object>
{
{"str", "thestring"},
{"byte", (byte)42},
{"bytearray", new byte[]{ 0x1, 0x2, 0x3}}
}
};
var col = new MongoClient("mongodb://localhost:27017").GetDatabase("test").GetCollection<DTO>("test");
col.InsertOne(instance);
}
}
我得到了:
{
"_id" : ObjectId("56a9eeeacdc5b3ea38c0a522"),
"Data" : {
"str" : "thestring",
"byte" : {
"_t" : "System.Byte",
"_v" : NumberInt(42)
},
"bytearray" : {
"_t" : "System.Byte[]",
"_v" : BinData(0, "AQID")
}
}
}
如您所见,"byte"和"bytearray"字段使用鉴别器"_"和"_v"序列化。但我期待这样的东西:
{
"_id" : ObjectId("56a9eeeacdc5b3ea38c0a522"),
"Data" : {
"str" : "thestring",
"byte" : 42,
"bytearray" : BinData(0, "AQID"))
}
}
我怎样才能做到这一点?
如果可以使用 Newtonsoft 对对象进行序列化和反序列化,则 Newtonsoft 是序列化操作的最佳解决方案。你能试试下面的代码吗?
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DictionaryTest
{
class Program
{
public class DTO
{
public string Name { get; set; }
public Dictionary<string, object> Data { get; set; }
}
static void Main(string[] args)
{
//var dictSerializer = new DictionaryInterfaceImplementerSerializer<Dictionary<string, object>>(DictionaryRepresentation.Document);
//BsonClassMap.RegisterClassMap<DTO>(cm => cm.MapMember(dto => dto.Data).SetSerializer(dictSerializer));
DTO instance = new DTO
{
Name = "test",
Data = new Dictionary<string, object>
{
{"str", "thestring"},
{"byte", (byte)42},
{"bytearray", new byte[]{ 0x1, 0x2, 0x3}}
}
};
string serializedOne = JsonConvert.SerializeObject(instance);
var col = new MongoClient("mongodb://localhost:27017").GetDatabase("test").GetCollection<DTO>("test");
col.InsertOne(serializedOne);
Console.WriteLine(serializedOne);
Console.ReadKey();
}
}
}
PS:我不是MongoDB专家,我记得我过去成功地完成了类似的事情。
Newtonsoft.JSON 官方页面:http://www.newtonsoft.com/json
Newtonsoft.JSON NuGet Page: https://www.nuget.org/packages/Newtonsoft.Json/
希望这对你有帮助