我有一个 REST 服务返回包含int
. 目标代码如下
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);
}