0

我已经定义了一个类,它只包含字典类型字典的一个成员。我想将其序列化以JSON格式化并因此使用JavaScriptSerializer.

[Serializable]
class X
{
    private readonly Dictionary<string, Dictionary<string, string>> dic;

    public X()
    {
        dic = new Dictionary<string, Dictionary<string, string>>();
    }

    public void Add()
    {
        this.dic.Add("x", new Dictionary<string, string>() { { "a", "b" } });
    }
}


class Program
{
    static void Main(string[] args)
    {
        var x = new X();
        x.Add();
        string msg = new JavaScriptSerializer(new SimpleTypeResolver()).Serialize(x);
        var y = new JavaScriptSerializer(new SimpleTypeResolver()).Deserialize<X>(msg);
    }
}

现在,上面的代码运行成功,没有任何错误/异常,但结果并不例外。上述代码中X类的序列化字符串为

{"__type":"Testing.X, Testing, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"}

谁能告诉我上面的代码有什么问题以及我缺少什么?另外,如果在上面的类中,我将内部字典类型更改为Dictionary<string, IEntity>我必须做的所有事情来序列化它。

4

1 回答 1

0

JavaScriptSerializer旨在默认情况下仅提取公共属性。通过 getter 或 setter 公开该字段后,您应该能够序列化此数据。

[Serializable]
class X
{
    private readonly Dictionary<string, Dictionary<string, string>> dic;

    public X()
    {
        dic = new Dictionary<string, Dictionary<string, string>>();
    }

    public void Add()
    {
        this.dic.Add("x", new Dictionary<string, string>() { { "a", "b" } });
    }

    //Property exposing private field 'dic'.
    public Dictionary<string, Dictionary<string, string>> Dictionary
    {
        get
        {
            return dic;
        }
    }
}


class Program
{
    static void Main(string[] args)
    {
        var x = new X();
        x.Add();
        string msg = new JavaScriptSerializer(new SimpleTypeResolver()).Serialize(x);
        var y = new JavaScriptSerializer(new SimpleTypeResolver()).Deserialize<X>(msg);
    }
}

在这种情况下,字符串包含以下输出(查看最后):

{"__type":"ConsoleApplication1.X, ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null","Dictionary":{"x":{"a":"b"}}}
于 2013-09-28T19:16:23.287 回答