使用RestSharp序列化具有一个值的对象集合

时间:2015-11-10 23:01:48

标签: c# xml xml-serialization restsharp

我需要下一个xml数据:

<trackingrequest>
    <user>USERNAME</user>
    <password>PASSWORD</password>
    <trackingnumbers>
        <trackingnumber>12345678901</trackingnumber>
    </trackingnumbers>
</trackingrequest>

为此,我创建了下一个模型:

[SerializeAs(Name = "trackingrequest")]
public class DpdTrackingRequest
{
    [SerializeAs(Name = "user")]
    public string User { get; set; }

    [SerializeAs(Name = "password")]
    public string Password { get; set; }

    [SerializeAs(Name = "trackingnumbers")]
    [XmlArrayItem("trackingnumber")]
    public IList<DpdTrackingNumber> TrackingNumbers { get; set; }
}

public class DpdTrackingNumber
{
    public string Value { get; set; }
}

但是当我调用AddXmlBody方法时,我会看到下一个结果:

<trackingrequest>
    <user>USERNAME</user>
    <password>PASSWORD</password>
    <trackingnumbers>
        <DpdTrackingNumber>
            <Value>12345678901</Value>
        </DpdTrackingNumber>
    </trackingnumbers>
</trackingrequest>

如何在<DpdTrackingNumber><Value>12345678901</Value></DpdTrackingNumber>中合并<trackingnumber>12345678901</trackingnumber>

1 个答案:

答案 0 :(得分:2)

为了达到您的要求,我认为您必须将System.Xml.Serialization.XmlTextAttribute设置为DpdTrackingNumber.Value属性。

但是,RestRequest的{​​{1}}默认为XmlSerializer,无法读取RestSharp.Serializers.XmlSerializer属性。
因此,在调用System.Xml.Serialization方法之前,您必须将XmlSerializer重置为RestSharp.Serializers.DotNetXmlSerializer

AddXmlBody

此外,您可能需要将dpdTrackingRequest.TrackingNumbers = new List<DpdTrackingNumber>(); dpdTrackingRequest.TrackingNumbers.Add(new DpdTrackingNumber { Value = "12345678901" }); RestRequest restRequest = new RestRequest(); // reset XmlSerializer restRequest.XmlSerializer = new RestSharp.Serializers.DotNetXmlSerializer(); var result = restRequest.AddXmlBody(dpdTrackingRequest); 的类型从TrackingNumbers更改为IList,因为List无法对接口进行序列化,因此DotNetXmlSerializer类如下:

DpdTrackingRequest