0

Hi I need return 2D array from ASP.NET web service.

First I tried this solution:

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

I got error:

Cannot serialize object of type System.String[,]. Multidimensional arrays are not supported.

It is Ok, so I tried this way.

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

I got this error:

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()

How can I serialize "2D array"? I need return from web method "2D array".

user1106231
  • 21
  • 1
  • 3

1 Answers1

0

Use a wrapper class for string[] and return an array of it

[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);
L.B
  • 114,136
  • 19
  • 178
  • 224
  • I think he need serialize 2D array according WEB SERVICE STANDARD no do simole XML SERIALIZATION. – Mike Dec 21 '11 at 18:29