简体   繁体   English

使用JSON.NET进行序列化时隐藏C#属性

[英]Hiding C# properties when serialize with JSON.NET

How can we hide the C# property where serializing with JSON.NET library. 我们如何隐藏使用JSON.NET库进行序列化的C#属性。 Suppose, we have class Customer 假设我们有班级客户

public class Customer
{
   public int CustId {get; set;}
   public string FirstName {get; set;}
   public string LastName {get; set;}
   public bool isLocked {get; set;}
   public Customer() {}

}

public class Test
{
  Customer cust = new Customer();
  cust.CustId = 101;
  cust.FirstName = "John"
  cust.LastName = "Murphy"

  string Json = JsonConvert.SerializeObject(cust); 
}

JSON JSON

{   
    "CustId": 101,   
    "FirstName": "John",   
    "LastName": "Murphy",  
    "isLocked": false 
}

This object is converted to json, but i didn't specify the isLocked property. 此对象转换为json,但我没有指定isLocked属性。 As library will serialize the entire class, is there any way to ignore a property during json serialization process or if we can add any attribute on the property. 由于库将序列化整个类,有没有办法在json序列化过程中忽略属性或者我们可以在属性上添加任何属性。

EDIT : Also, If we create two instance of Customer class in an array. 编辑 :另外,如果我们在数组中创建两个Customer类实例。 if we didn't specify is locked property on the second instance, can we can property hide for second object. 如果我们没有指定第二个实例上的锁定属性,我们可以将属性隐藏为第二个对象。

JSON JSON

{
  "Customer": [
    {
      "CustId": 101,
      "FirstName": "John",
      "LastName": "Murphy",
      "isLocked": false
    },
    {
      "CustId": 102,
      "FirstName": "Sara",
      "LastName": "connie"
    }
  ]
}

Use the JSON.Net attributes: 使用JSON.Net属性:

public class Customer
{
   public int CustId {get; set;}
   public string FirstName {get; set;}
   public string LastName {get; set;}
   [JsonIgnore]
   public bool isLocked {get; set;}
   public Customer() {}

}

For more information: https://www.newtonsoft.com/json/help/html/SerializationAttributes.htm 有关更多信息: https//www.newtonsoft.com/json/help/html/SerializationAttributes.htm

Yes, marking your properties with JsonIgnore is probably best. 是的,用JsonIgnore标记你的属性可能是最好的。

However, if you do want to chose at runtime, add a public bool ShouldSerialize{MemberName} to your class. 但是,如果您确实想在运行时选择,请在您的类中添加一个public bool ShouldSerialize{MemberName} When JSON.net Serialises it will call it, and if false, not serialise. 当JSON.net Serialises时,它将调用它,如果为false,则不会序列化。 isLocked is false by default, perhaps you do want to serialise it when its true, for example. 默认情况下, isLocked为false,例如,或许您确实想要将其序列isLocked true。

使用JsonIgnore属性标记该属性。

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

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