加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 19:52:24 所属栏目:百科 来源:网络整理
导读:我们如何隐藏使用 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()
我们如何隐藏使用 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,
“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() {}

}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读