簡體   English   中英

使用JSON.NET進行序列化時隱藏C#屬性

[英]Hiding C# properties when serialize with JSON.NET

我們如何隱藏使用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); 
}

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

使用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

是的,用JsonIgnore標記你的屬性可能是最好的。

但是,如果您確實想在運行時選擇,請在您的類中添加一個public bool ShouldSerialize{MemberName} 當JSON.net Serialises時,它將調用它,如果為false,則不會序列化。 默認情況下, isLocked為false,例如,或許您確實想要將其序列isLocked true。

使用JsonIgnore屬性標記該屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM