当前位置: 首页 > 知识库问答 >
问题:

xml用泛型类型序列化泛型类

朱起运
2023-03-14

我需要将包含类型为Pair的对象的列表序列化为xml

首先,我创建了一个类PairList来保存对的列表,然后我创建了一个实际的类,它表示一对两个值,key和value。

 [XmlRoot("pairList")]
        public class PairList<T,U>{
            [XmlElement("element")]
            public List<Pair<T,U>> list;
            public PairList()
            {
                list = new List<Pair<T, U>>();
            }

        }
        public class Pair<T, U>
        {
            [XmlAttribute("key")]
            public T key;
            [XmlAttribute("value")]
            public U value;
            [XmlAttribute("T-Type")]
            public Type ttype;
            [XmlAttribute("U-Type")]
            public Type utype;

            public Pair()
            {
            }
            public Pair(T t, U u)
            {
                key = t;
                value = u;
                ttype = typeof(T);
                utype = typeof(U);
            }
        }

然后,我尝试序列化它:

 PairList<string,int> myList = new PairList<string,int>();
            myList.list.Add(new Pair<string, int>("c", 2));
            myList.list.Add(new Pair<string, int>("c", 2));
            myList.list.Add(new Pair<string, int>("c", 2));
            myList.list.Add(new Pair<string, int>("c", 2));
            try
            {
                XmlSerializer serializer = new XmlSerializer(typeof(PairList<string, int>));
                TextWriter tw = new StreamWriter("list.xml");
                serializer.Serialize(tw, myList);
                tw.Close();
            }
            catch (Exception xe)
            {
                MessageBox.Show(xe.Message);
            }

不幸的是,我遇到了一个异常有一个错误反映类型:PairList[System.String,System.Int32]。欢迎任何关于如何避免此异常并序列化该类的想法。

如果我选择不序列化ttype和utype字段(通过将其设置为受保护或私有),则序列化有效。我不明白为什么它不想序列化类型字段。

共有1个答案

邢凌
2023-03-14

将您的班级改为

public class Pair<T, U>
{
    [XmlAttribute("key")]
    public T key;
    [XmlAttribute("value")]
    public U value;
    [XmlAttribute("T-Type")]
    public string ttype;
    [XmlAttribute("U-Type")]
    public string utype;

    public Pair()
    {
    }
    public Pair(T t, U u)
    {
        key = t;
        value = u;
        ttype = typeof(T).ToString();
        utype = typeof(U).ToString();
    }
}

它应该可以工作。您不能使用Xmlseralizer序列化/反序列化Type。(例如,假设T是在外部程序集中定义的复杂对象,并且您要反序列化的计算机上不存在此程序集)

 类似资料:
  • 问题内容: 我正在尝试制作一个使用Jackson来反序列化POJO的类。 看起来像这样… 我对此实施有2个问题。 首先是我将类类型传递给方法,以便对象映射器知道应反序列化的类型。有使用泛型的更好方法吗? 同样在get方法中,我将一个从objectMapper返回的对象强制转换为T。这看起来特别讨厌,因为我必须在此处强制转换T,然后还必须从调用它的方法中强制转换对象类型。 我在该项目中使用了Robo

  • 我用Jackson编写了自己的序列化程序。它接受一个变量或类,并返回任何简单类型的值。 示例:serialize(new MyClass(2.0))将返回一个值为 2.0 的双精度值,其中 MyClass 如下所示: 因此,为了获得正确的值,我需要设置@JsonValue,但是,当我序列化一个没有@JsonValue注释的对象(例如UUID)时,它会返回预期的UUID字符串。 创建我自己的类没有@

  • 我在Android应用程序中实现Json反序列化时遇到了一些问题(带有Gson库)

  • 我有一个关于Java仿制药的问题。假设我有以下方法: 我如何用通配符<解释上面的类型转换?扩展U>?使用它与只使用有什么区别?

  • 给定这样一个类 如何实现可以处理嵌套泛型类型的自定义Kafka反序列化器? 附注:我正在使用jackson进行序列化/反序列化。