Hiding C # properties when serialized with JSON.NET

How can we hide the C # property when serialized with the JSON.NET library. Suppose we have a 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

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

This object is converted to json, but I did not specify the isLocked property. Since the library will serialize the entire class, is there a way to ignore the property during the json serialization process, or can we add some attribute to this property.

EDIT : Also, if we create two instances of the Customer class in the array. if we did not define the locked property in the second instance, can we hide the property for the second object.

Json

{
  "Customer": [
    {
      "CustId": 101,
      "FirstName": "John",
      "LastName": "Murphy",
      "isLocked": false
    },
    {
      "CustId": 102,
      "FirstName": "Sara",
      "LastName": "connie"
    }
  ]
}
+7
source share
3

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() {}

}

: https://www.newtonsoft.com/json/help/html/SerializationAttributes.htm

+16

, JsonIgnore.

, , public bool ShouldSerialize{MemberName} . JSON.net Serialises , false, . isLocked , , , , .

+8

Mark this property with an attribute JsonIgnore.

+3
source

Source: https://habr.com/ru/post/1545232/


All Articles