简体   繁体   中英

Serializing multiple nested XmlArrays in C#

I am trying to do serialize a class that contains a List with nested Tuples with arrays of DateTimes as keys and doubles as values.

Below is a basic version of the code:

Class:

[XmlRoot("Foo")]
public class Foo
{
    [XmlArray("Pairs")]
    [XmlArrayItem(typeof(Tuple<DateTime[], double>), ElementName = "Pair")]
    [XmlArrayItem(typeof(DateTime), ElementName = "DateRange"), XmlArrayItem(typeof(double), ElementName = "Value")]
    public List<Tuple<DateTime[], double>> pairs;
}

Main:

class Program
{
    static void Main(string[] args)
    {
        Foo f = new Foo();
        f.pairs = new List<Tuple<DateTime[], double>>();

        f.pairs.Add(
            new Tuple<DateTime[], double>(
                new DateTime[2]{
                    new DateTime(2014,1,1),
                    new DateTime(2014,1,3),
                },
                1.1
            ));

        f.pairs.Add(
            new Tuple<DateTime[], double>(
                new DateTime[2]{
                    new DateTime(2014,2,1),
                    new DateTime(2014,2,3),
                },
                2.2
            ));

        System.Xml.Serialization.XmlSerializer writer =
            new System.Xml.Serialization.XmlSerializer(typeof(Foo));

        System.IO.StreamWriter file = new System.IO.StreamWriter(
            @"C:/Users/x/Desktop/test.xml");


    }
}

I am getting a reflecting error and I think the issue is that I am not using the attributes correctly as there are too many nested arrays.

Is there a way to make this work, or would I need to create separate serializable classes and nest those within one another?

The error I'm getting is not about nested arrays. When you look at the Inner exceptions you will eventually arrive at:

System.Tuple`2[System.DateTime[],System.Double] cannot be serialized 
because it does not have a parameterless constructor.

Why I could not serialize a tuple in C#?

So I am afraid you will have to change your designs ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM