简体   繁体   中英

XmlSerializer throwing exception with generic list during serialization

I'm attempting to serialize (and subsequently deserialize) a rather simple class to an XML string, but am getting an exception: "The type System.Collections.Generic.List`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] may not be used in this context."

The method I'm using to serialize is:

public string ToXml(TaskListFilterConfig config)
{
    Type[] extraTypes = { typeof(FilterConfig), typeof(SortConfig) };

    XmlSerializer serializer = new XmlSerializer(config.GetType(), extraTypes);

    using (StringWriter writer = new StringWriter())
    {
        serializer.Serialize(writer, config);

        return writer.ToString();
    }
}

The classes I'm attempting to serialize are:

[XmlRoot(ElementName = "TaskListFilterConfig", IsNullable = false)]
[XmlInclude(typeof(FilterConfig))]
[XmlInclude(typeof(SortConfig))]
public class TaskListFilterConfig
{
    [XmlArray("FilterConfigList")]
    [XmlArrayItem("FilterConfig")]
    public List<FilterConfig> FilterConfigList { get; set; }

    [XmlArray("SortConfigList")]
    [XmlArrayItem("SortConfig")]
    public List<SortConfig> SortConfigList { get; set; }

    public TaskListFilterConfig() 
    {
        FilterConfigList = new List<FilterConfig>();
        SortConfigList = new List<SortConfig>();
    }
}


[XmlType("FilterConfig")]
public class FilterConfig
{

    public OperandType Operand { get; set; }

    public int SelectedOperatorIndex { get; set; }

    public int SelectedColumnIndex { get; set; }

    public object RightOperand { get; set; }

    public FilterConfig() { }
}

[XmlType("SortConfig")]
public class SortConfig
{
    public Infragistics.Windows.Controls.SortStatus SortDirection { get; set; }

    public int ColumnSelectedIndex { get; set; }

    public SortConfig() { }
}

Your Class Model and Searalizable data are wrong.

Notice that TaskListFilterConfig is a different type than extraTypes . extraTypes has some other model data.

If you want to serialize TaskListFilterConfig class and Data: Use below Code

public string ToXml(TaskListFilterConfig config)
{
    XmlSerializer serializer = new XmlSerializer(typeOf(TaskListFilterConfig));
    using (StringWriter writer = new StringWriter())
    {
        serializer.Serialize(writer, config);
        return writer.ToString();
    }
}

Or if you want extraTypes pass the relevent model data as well.

I know it's a very late answer. Just want to make sure the question has answered. Maybe it help will someone in the future. :)

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