【问题标题】:Hiding C# properties when serialize with JSON.NET使用 JSON.NET 序列化时隐藏 C# 属性
【发布时间】:2019-08-20 13:05:47
【问题描述】:

我们如何隐藏使用 JSON.NET 库进行序列化的 C# 属性。假设,我们有类 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 
}

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

编辑: 此外,如果我们在数组中创建 Customer 类的两个实例。如果我们没有在第二个实例上指定 is locked 属性,我们可以隐藏第二个对象的属性吗?

JSON

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

【问题讨论】:

    标签: c# visual-studio serialization properties json.net


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      是的,最好用JsonIgnore 标记您的属性。

      但是,如果您确实想在运行时进行选择,请将 public bool ShouldSerialize{MemberName} 添加到您的类中。当 JSON.net 序列化时,它将调用它,如果为 false,则不序列化。 isLocked 默认为 false,例如,当它为 true 时,您可能确实想将其序列化。

      【讨论】:

      • 如果您很容易使用哪些工具,Javascriptserializer 提供了一种更简洁、更 linq-y 的方式来决定在运行时序列化什么。像这样:string jsonString = serializer.Serialize(customers.Select(x => x.CustId)); 只序列化CustId
      • 如果有的话,能给个简单的例子或链接吗?
      • @A.P.S - JavaScriptSerializer Class。需要明确的是:这是一种 alternative 方法。在使用javascriptserializer之前,我会调查:newtonsoft的JSON Serialization AttributesJsonConverter,以及上面提到的ShouldSerialize
      【解决方案3】:

      使用JsonIgnore 属性标记该属性。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-06-08
        • 1970-01-01
        • 2012-04-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多