Serialize/Deserialize different property names?

只愿长相守 提交于 2019-12-11 10:36:19

问题


I have an old system which in a request info call returns xml with names that look like:

postalCodeField, firstNameField...

That same system then has a modify call which takes xml that looks like:

PostalCode, fistName, lastName....

Is there a way to build an object that would deserialize the request, yet serialize the xml output with different names?

Specifically:

public class RequestInfo
{
    public string firstNameField{get;set;}
    public string lastNameField{get;set;}
}

public class ModifyInfo
{
    public string firstName{get;set;}
    public string lastName{get;set;}
    public ModifyInfo(){}
    public ModifyInfo(RequestInfo ri)
    {
        firstName = ri.firstNameField
        .....
    }
}

Is there a way through say attributes to make these into the same object?

EDIT

Is there a way to have a single object that would accept one tag name on deserialize, then output a different name on serialize?

< myTagField /> (deserialize to) myObj.MyTag (serialize to) < MyTag />


回答1:


It's important to note which actual serializer you're using. Every different serializer works differently.

I assume you're using the System.Xml.Serialization.XmlSerializer. If that is the case, then you want to use the attributes in the System.Xml.Serialization namespace such as XmlElementAttribute like so:

public class Person
{
    [System.Xml.Serialization.XmlElement(ElementName = "firstNameField")]
    public string FirstName { get; set; }
}

This assumes the field is an XML element. If it's an attribute, use the XmlAttribute attribute.




回答2:


Check Attributes That Control XML Serialization on MSDN. You will need XmlElement for properties and, possibly, XmlRoot for root class.

If you need to override property names only during deserialization, than you can define attributes dynamically, using XmlAttributeOverrides:

public XmlSerializer CreateOverrider()
{
    XmlElementAttribute xElement = new XmlElementAttribute();
    xElement.ElementName = "firstName"; 

    XmlAttributes xElements = new XmlAttributes();
    xElements.XmlElements.Add(xElement);

    XmlAttributeOverrides xOver = new XmlAttributeOverrides();
    xOver.Add(typeof(RequestInfo), "firstNameField", xElements);

    XmlSerializer xSer = new XmlSerializer(typeof(RequestInfo), xOver);
    return xSer;
}


来源:https://stackoverflow.com/questions/19142691/serialize-deserialize-different-property-names

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!