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"
}
]
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With