忽略在XML串行化的财产,但不反序列化过程 [英] Ignore a property during xml serialization but not during deserialization

查看:185
本文介绍了忽略在XML串行化的财产,但不反序列化过程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,我怎样才能使XmlSerializer的序列化过程中而不是反序列化过程中忽略的属性? (或者我怎么做同样的Json.net?)

In C#, how can I make XmlSerializer ignore a property during serialization but not during deserialization? (Or how do I do the same with Json.net?)

要prevent被序列化的属性,你可以添加 XmlIgnore 属性:

To prevent a property from being serialized, you can add the XmlIgnore attribute:

[XmlIgnore]
public int FooBar {get;set;}

这将导致< FooBar的> 序列化过程中被忽略的标签

This will cause the <FooBar> tag to be omitted during serialization.

不过,这也意味着&LT; FooBar的&GT; 标记将反序列化过程中会忽略

However, this also means that the <FooBar> tag will be ignored during deserialization.

在我的情况,我接受的项目从用户请求一个数组,并为每个项目的用户,如果他们要添加,修改或删除项目可以指定action属性。我想使用GET名单打电话同一个模型对象,而不想回到这个动作属性。我希望这将是一个pretty的常见情况。

In my case, I accept an array of items from user in the request, and for each item user can specify an action property if they want to add, modify or delete the item. I want to use the same model object for GET list calls, and don't want to return this action property. I expect this would be a pretty common case.

另一个用例: 假设你有一个圆形物体

Another use case: say you have a circle object

public class Circle
{
    public double Radius { get; set; }
}

和修改它来添加一个直径财产

and you modify it to add a diameter property

public class Circle2
{
    public double Diameter { get; set; }
    public double Radius { get { return Diameter / 2; } set { Diameter = value*2; } }
}

您可能希望只序列化的直径,但仍然可以反序列化只包含半径旧格式的XML文件。

You may want to serialize only the diameter, but still be able to deserialize xml files in the old format that contain only the radius.

我做我的研究,并没有发现任何东西,因此这个问题

I did my research and didn't find anything, hence this question

解决方案:我想出的解决方案。我可以在这个MSDN文档

Solution: I figured out the solution. I can add a ShouldSerialize property which always return false, details at this MSDN documentation

(此解决方案可以加入,如果这个问题被重新打开一个实际的答案)

推荐答案

如果你想忽略元素的序列化与XmlSerializer的,你可以使用XmlAttributeOverrides:

If you want to ignore the element at serialization with XmlSerializer, you can use XmlAttributeOverrides:

XmlAttributeOverrides overrides = new XmlAttributeOverrides();
XmlAttributes attribs = new XmlAttributes();
attribs.XmlIgnore = true;
attribs.XmlElements.Add(new XmlElementAttribute("YourElementName"));
overrides.Add(typeof(YourClass), "YourElementName", attribs);

XmlSerializer ser = new XmlSerializer(typeof(YourClass), overrides);
ser.Serialize(...

这篇关于忽略在XML串行化的财产,但不反序列化过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆