反序列化包含int列表的对象

时间:2012-11-01 18:52:45

标签: c#

我有一个REST服务返回包含int列表的序列化对象的XML。目标代码在

之下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Serialization;

namespace All.Tms.Dto
{
    [XmlRoot(Namespace = "http://schemas.datacontract.org/2004/07/All.Tms.Dto")]
    public class ReadSensorsForVehicleIdResponse
    {
        public List<int> sensorIdList { get; set; }
    }
}

当序列化此对象时,将生成XML并将其发送为:

<ReadSensorsForVehicleIdResponse xmlns="http://schemas.datacontract.org/2004/07/All.Tms.Dto"      xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><sensorIdList xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays"><a:int>107</a:int></sensorIdList></ReadSensorsForVehicleIdResponse>

问题是int值被序列化为

<a:int>107</a:int> 

这会导致对象的反序列化失败。当我改变

<a:int>107</a:int> 

<int>107</int> 

对象正确反序列化。是否有任何理由将int值以这种方式序列化,以及如何解决此问题?

以下是我用来反序列化的代码

public static T Deserialize<T>(string xml) where T : class
    {
        var serializer = new XmlSerializer(typeof(T));

        var stream = new MemoryStream(Encoding.UTF8.GetBytes(xml));

        var reader = XmlReader.Create(stream);

        return (T)serializer.Deserialize(reader);
    }

2 个答案:

答案 0 :(得分:3)

这是一个正在应用的xml命名空间

xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays"

在反序列化期间,您需要考虑命名空间。

答案 1 :(得分:2)

Linq To Xml易于使用

var xDoc = XDocument.Parse(xmlstring); //or XDocument.Load(fileName)
XNamespace ns = "http://schemas.microsoft.com/2003/10/Serialization/Arrays";

var a = xDoc.Descendants(ns + "int")
            .Select(x => (int)x)
            .ToList();
相关问题