A.P.S
A.P.S

Reputation: 1164

Hiding C# properties when serialize with JSON.NET

How can we hide the C# property where serializing with JSON.NET library. 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

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

This object is converted to json, but i didn't specify the isLocked property. 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.

EDIT: Also, If we create two instance of Customer class in an array. if we didn't specify is locked property on the second instance, can we can property hide for second object.

JSON

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

Upvotes: 20

Views: 27507

Answers (3)

Bun
Bun

Reputation: 1495

Use the JSON.Net attributes:

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

Upvotes: 34

Nathan
Nathan

Reputation: 6531

Yes, marking your properties with JsonIgnore is probably best.

However, if you do want to chose at runtime, add a public bool ShouldSerialize{MemberName} to your class. When JSON.net Serialises it will call it, and if false, not serialise. isLocked is false by default, perhaps you do want to serialise it when its true, for example.

Upvotes: 13

dcastro
dcastro

Reputation: 68690

Mark that property with the JsonIgnore attribute.

Upvotes: 3

Related Questions