【问题标题】:ISerializable - serialise a recursive object type eg, a MapISerializable - 序列化递归对象类型,例如 Map
【发布时间】:2012-02-15 12:17:37
【问题描述】:

我正在尝试使用 WCF 和 C# 创建一个 Web 服务来向 AJAX 客户端呈现一些数据。

我希望我的数据像这样返回(JSON):

{"Settings":{"LAN":{"IPAddress":"10.0.0.1", "SubnetMask":"255.255.255.0"},"WAN":{"Status":"Up"}}}

我已经创建了一个简单的JsonMap 类:

[Serializable]
public class JsonMap :ISerializable
{
    Dictionary<string, JsonMap> children { get; set; }
    public string Value { get; set; }

    public JsonMap()
    {
        this.children = new Dictionary<string, JsonMap>();
        this.Value = string.Empty;
    }

    public JsonMap this[string key]
    {
        get
        {
            if (!this.children.ContainsKey(key))
                this.children[key] = new JsonMap();
            return this.children[key];
        }
        set
        {
            this.children[key] = value;
        }
    }

    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        foreach (string key in this.children.Keys)
            if (this[key].children.Keys.Count == 0)
                info.AddValue(key, this[key].Value);
            else
                info.AddValue(key, this[key]);
    }
}

理论上,当JsonMap 类被序列化时,它应该检查孩子是否也是父母,如果是则渲染它们 - 或者渲染孩子的值。

但是 - 当通过 WCF 运行它时,它崩溃了,我没有返回任何数据。

我在这里遗漏了什么明显的东西吗?

【问题讨论】:

  • “它崩溃了” - 究竟发生了什么,您使用的是什么序列化程序?例如,对于 DataContractSerializer,我怀疑它是否正在查看您的 ISerializable 代码。好消息是没有“父”键,所以它不应该是通常的父/子循环。但是,如果你有一个真正的循环,所有的赌注都没有。
  • 您可能错过了这样一个事实,即 .NET 中有不止一种序列化程序,而且 WCF 通常根本不使用 ISerializable

标签: c# wcf serialization recursion


【解决方案1】:

这就是我序列化到 Json 的方式,它不能回答你的问题,可能没用,但可能会有所帮助.. 以防万一:

System.Web.Script.Serialization.JavaScriptSerializer o = new System.Web.Script.Serialization.JavaScriptSerializer();

string JsonString = o.Serialize(MyObject);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    • 2021-06-24
    • 2015-10-02
    • 2011-10-04
    • 1970-01-01
    • 2016-11-06
    • 1970-01-01
    相关资源
    最近更新 更多