简体   繁体   English

反序列化时从类中删除/隐藏/删除字段

[英]Removing/Hiding/Deleting a field from class when deserialising

I have a class - say Place 我上课-说地点

public class Place{
    public int id;
    public string name;
    public string slug;
}

There are other classes like City, State, Country which are derived from Place class. 还有其他一些类,例如城市,州,国家/地区,这些类是从地方类派生的。

I get an XML string like this, that has array of cities 我得到这样的XML字符串,其中包含城市数组

<cities>
 <City>
  <name>
   <![CDATA[Mumbai]]>
  </name>
  <slug>
   <![CDATA[mumbai]]>
  </slug>
 </City>
<City>
  <name>
   <![CDATA[Thane]]>
  </name>
  <slug>
   <![CDATA[thane]]>
  </slug>
 </City>
</cities>

I deserialize this string in the city array and send to Angular UI. 我在城市数组中反序列化此字符串,然后将其发送到Angular UI。

On the frontend, there is no use of id field. 在前端,没有使用id字段。 But since it is part of class, the empty/null id field also gets deserialize. 但是由于它是类的一部分,所以空/空id字段也将反序列化。 I can remove the id field from the class, but it is used in other functions so I cannot do that. 我可以从类中删除id字段,但是它在其他函数中使用,所以我不能这样做。 I don't want to use XmlIgnore attribute because some one might have already used this field in other functions. 我不想使用XmlIgnore属性,因为某些人可能已经在其他函数中使用了此字段。

My question is, is there a way to remove the id field before sending it forward? 我的问题是,有没有办法在向前发送ID字段之前将其删除?

return Serializer.DeserializeXml<Cities>(_strCities);

You can use [XmlIgnore] and [ScriptIgnore] attributes above property 您可以在属性上方使用[XmlIgnore]和[ScriptIgnore]属性

[XmlIgnore]
[ScriptIgnore]
public int intvar{get;set;}

The solution was quite simple. 解决方案非常简单。 I had to add another function - ShouldSerializePropertyName. 我必须添加另一个功能-ShouldSerializePropertyName。 The function will return true or false and depending on the result the id will be serialized or deserialized :) 该函数将返回true或false,并根据结果将id序列化或反序列化:)

public bool ShouldSerializeid()
        {
            return !(id.Equals(string.Empty)|| id.Equals(0));
        }

I found this explanation on MSDN - 我在MSDN上找到了这种解释-

ShouldSerialize and Reset are optional methods that you can provide for a property, if the property does not a have simple default value. 如果属性没有简单的默认值,则ShouldSerialize和Reset是可以为属性提供的可选方法。 If the property has a simple default value, you should apply the DefaultValueAttribute and supply the default value to the attribute class constructor instead. 如果属性具有简单的默认值,则应应用DefaultValueAttribute并将默认值提供给属性类构造函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM