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

A.P*_*P.S 7 c# serialization properties json.net visual-studio

我们如何隐藏使用JSON.NET库进行序列化的C#属性.假设我们有班级客户

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); 
}
Run Code Online (Sandbox Code Playgroud)

JSON

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

此对象转换为json,但我没有指定isLocked属性.由于库将序列化整个类,有没有办法在json序列化过程中忽略属性或者我们可以在属性上添加任何属性.

编辑:另外,如果我们在数组中创建两个Customer类实例.如果我们没有指定第二个实例上的锁定属性,我们可以将属性隐藏为第二个对象.

JSON

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

谢谢

Bun*_*Bun 16

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

}
Run Code Online (Sandbox Code Playgroud)

有关更多信息:http://james.newtonking.com/json/help/index.html?topic = html/SerializationAttributes.htm


Nat*_*per 8

是的,标记您的房产JsonIgnore可能是最好的.

但是,如果您确实想在运行时选择,public bool ShouldSerialize{MemberName}请在课程中添加.当JSON.net Serialises时,它将调用它,如果为false,则不会序列化.isLocked默认情况下为false,例如,您可能希望在其为true时将其序列化.