在 xml 序列化期间忽略属性,但在反序列化期间不忽略

时间:2023-04-26
本文介绍了在 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?)

要防止属性被序列化,可以添加 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.

不过,这也意味着<FooBar>标签在反序列化时会被忽略.

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

在我的例子中,我在请求中接受来自用户的一组项目,如果用户想要添加、修改或删除项目,他们可以为每个项目指定一个操作属性.我想对 GET 列表调用使用相同的模型对象,并且不想返回此操作属性.我预计这将是一个很常见的情况.

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 序列化期间忽略属性,但在反序列化期间不忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:在 C# 中使用 newtonsoft 查找并返回 JSON 差异? 下一篇:asp.net core 1.0 web api使用camelcase

相关文章