JsonIgnore和JsonProperty用法

public class Student
{
  public string Name { get; set; }

  [Newtonsoft.Json.JsonIgnore]
  public int Age { get; set; }

  public bool Sex { get; set; }

  [JsonProperty("Others")]
  public string Address { get; set; }
}

Student stu = new Student()
{
  Name = "张三",
  Age = 18,
  Sex = true,
  Address = "上海"
};

var stuJson = JsonConvert.SerializeObject(stu, Formatting.Indented);

输出结果:

{
  "Name": "张三",
  "Sex": true,
  "Others": "上海"
}

总结:

JsonIgnore用于在输出的json中隐藏对象的相关属性

JsonProperty用于在输出的json中对对象的相关属性进行重命名

 

posted @ 2021-06-25 16:28  WoodLeaf  阅读(322)  评论(0)    收藏  举报