bak*_*san 5 c# serialization json dictionary
我有一个当前从 Dictionary 继承的类,然后向其中添加了一些第一类成员属性。大致:
public class Foo : Dictionary<string, string>
{
public string Bar { get; set; }
public string Baz { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
然而,将此对象的实例序列化为 JSON 后,序列化程序似乎只发出我存储在字典中的键/值对。即使我将 DataMember 属性应用于新的第一类属性,JSON 序列化程序似乎也不知道如何处理这些属性,而是忽略它们。
我假设我缺少一些基本的基本知识,但是在 .net 的 JSON 序列化器上搜索代码示例和文档时,我只发现了一些与我正在做的事情不太匹配的琐碎示例。我们从其他基类派生的所有其他类似乎都没有表现出这个问题,特别是从通用字典派生的这个类让我们感到不舒服。
[编辑] 除了将字典作为一流属性移入 Foo 之外,还有什么办法可以实现这一点吗?我假设挂断是序列化器不知道如何“命名”字典以将其与其他成员区分开来?
在这种情况下,基于组合的解决方案可能会更好:
using System;
using System.Collections.Generic;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
class Program
{
static void Main()
{
Foo foo = new Foo { Bar = "bar", Baz = "baz" };
foo.Items.Add("first", "first");
DataContractJsonSerializer serializer
= new DataContractJsonSerializer(typeof(Foo));
using (MemoryStream ms = new MemoryStream())
{
serializer.WriteObject(ms, foo);
Console.WriteLine(Encoding.Default.GetString(ms.ToArray()));
}
}
}
public class Foo
{
public Dictionary<string, string> Items { get; set; }
public string Bar { get; set; }
public string Baz { get; set; }
public Foo()
{
this.Items = new Dictionary<string, string>();
}
}
Run Code Online (Sandbox Code Playgroud)
产生以下输出:
{"Bar":"bar","Baz":"baz","Items":[{"Key":"first","Value":"first"}]}
作为解决方法,这可以解决您的问题吗?
| 归档时间: |
|
| 查看次数: |
3744 次 |
| 最近记录: |