【问题标题】:ASP.NET web service serialize 2D arrayASP.NET Web 服务序列化二维数组
【发布时间】:2011-12-21 17:00:35
【问题描述】:

您好,我需要从 ASP.NET Web 服务返回二维数组。

首先我尝试了这个解决方案:

    [WebMethod]
    public string[,] ReturnMultiDimArray()
    {
        var x = new string[,] { { "ab" }, { "cd" } };
        return x;
    }

我收到错误:

无法序列化 System.String[,] 类型的对象。不支持多维数组。

没关系,所以我尝试了这种方式。

    [WebMethod]
    public string[][] ReturnMultiDimArray()
    {
        string[] y = { "ab", "cd" };
        string[] z = { "ef", "gh" };
        string[][] x = { y, z };
        return x;
    }

我收到了这个错误:

System.InvalidOperationException: There was an error generating the XML document. ---> System.InvalidCastException: Unable to cast object of type 'System.String[][]' to type 'System.Collections.Generic.List`1[System.Collections.Generic.List`1[System.String]]'.
   at Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriter1.Write5_ArrayOfArrayOfString(Object o)
   at Microsoft.Xml.Serialization.GeneratedAssembly.ListOfListOfStringSerializer4.Serialize(Object objectToSerialize, XmlSerializationWriter writer)
   at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
   --- End of inner exception stack trace ---
   at System.Xml.Serialization.XmlSerializer.Serialize(XmlWriter xmlWriter, Object o, XmlSerializerNamespaces namespaces, String encodingStyle, String id)
   at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o, XmlSerializerNamespaces namespaces)
   at System.Xml.Serialization.XmlSerializer.Serialize(TextWriter textWriter, Object o)
   at System.Web.Services.Protocols.XmlReturnWriter.Write(HttpResponse response, Stream outputStream, Object returnValue)
   at System.Web.Services.Protocols.HttpServerProtocol.WriteReturns(Object[] returnValues, Stream outputStream)
   at System.Web.Services.Protocols.WebServiceHandler.WriteReturns(Object[] returnValues)
   at System.Web.Services.Protocols.WebServiceHandler.Invoke()

如何序列化“二维数组”?我需要从网络方法“二维数组”返回。

【问题讨论】:

    标签: c# web-services xmlserializer multidimensional-array


    【解决方案1】:

    string[] 使用包装类并返回它的数组

    [Serializable]
    public class StringArray
    {
        public StringArray()
        {
        }
        public StringArray(params string[] arr)
        {
            this.Array = arr;
        }
        public string[] Array;
    }
    
    MemoryStream m = new MemoryStream();
    StringArray[] strArr = new StringArray[] { new StringArray("a", "b"), new StringArray("c", "d", "e") };
    XmlSerializer xs = new XmlSerializer(typeof(StringArray[]));
    xs.Serialize(m,strArr);
    

    【讨论】:

    • 我认为他需要根据 WEB SERVICE STANDARD 序列化二维数组 no do simole XML SERIALIZATION。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-27
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多