2011-12-21 91 views
0

嗨我需要從ASP.NET Web服務返回二維數組。ASP.NET Web服務序列化2D陣列

首先我想這個解決方案:

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

我如何序列化 「二維數組」?我需要從web方法「2D數組」返回。

回答

0

使用包裝類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); 
+0

一個數組,我認爲他需要根據Web服務規範沒有做simole XML序列化序列化二維數組。 – Mike 2011-12-21 18:29:25

+0

請參閱http://stackoverflow.com/a/553842/932418 – 2011-12-21 18:41:23