Xml Deserializer to deserialize 2-Dimensional Array

烈酒焚心 提交于 2019-12-12 02:35:56

问题


I have a problem about deserialize an array ( int[,]) I have an array int[*,*] and i need to serialize and deserialize it. How to do it with XMLSerializer??

    int[,] B = new int[2,5];        
    public int[,] XMLIntArray
    {
        set { B = value; }
        get { return B; }
    }

回答1:


Unfortunately multidimensional arrays serialization are not supported by XmlSerializer or DataContractSerializer the only way (not human readable) is to use binary serialization like in this example

   public static void Main()
    {

        int[,] B = new int[2, 5];
        B[0, 0] = 5;
        B[0, 1] = 3;
        B[0, 2] = 5;  

        DeepSerialize<int[,]>( B,"test3");
        int[,] des= DeepDeserialize<int[,]>("test3");



    }

 public static void DeepSerialize<T>(T obj,string fileName)
    {
        //            MemoryStream memoryStream = new MemoryStream();
        FileStream str = new FileStream(fileName, FileMode.Create);
        BinaryFormatter binaryFormatter = new BinaryFormatter();
        binaryFormatter.Serialize(str, obj);
        str.Close();
    }
    public static T DeepDeserialize<T>(string fileName)
    {
        //            MemoryStream memoryStream = new MemoryStream();
        FileStream str = new FileStream(fileName, FileMode.Open);

        BinaryFormatter binaryFormatter = new BinaryFormatter();
        T returnValue = (T)binaryFormatter.Deserialize(str);            
        str.Close();
        return returnValue; 
    }  



回答2:


You cannot serialze a int[,] but you can serialize a int[][]. Before serializing your array, just convert it like that:

var my2dArray = new int[2,5];
var myJaggedArray = new int [2][];

for(int i = 0 ; i < my2DArray.GetLength(0) ; i ++)
{
    myJaggedArray[i] = new int[my2DArray.GetLength(1)];

    for(int j = 0 ; j < my2DArray.GetLength(1) ; j ++)
        myJaggedArray[i][j] = my2DArray[i,j]; 
}


来源:https://stackoverflow.com/questions/20622005/xml-deserializer-to-deserialize-2-dimensional-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!