20

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"
    }
  ]
}

3 Answers 3

34

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

Sign up to request clarification or add additional context in comments.

Comments

13

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.

4 Comments

If you're easy on which tools to use, Javascriptserializer offers a neater, more linq-y way of deciding what to serialise at runtime. Like this: string jsonString = serializer.Serialize(customers.Select(x => x.CustId)); to only serialise CustId.
can you give simple example or link if there is any?
@A.P.S - JavaScriptSerializer Class. To be clear: that is an alternative approach. Before using javascriptserializer, I would investigate: newtonsoft's JSON Serialization Attributes and JsonConverter, as well as above mentioned ShouldSerialize.
3

Mark that property with the JsonIgnore attribute.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.