欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

使用JsonProperty Attribute修改返回json

程序员文章站 2022-09-10 14:53:33
使用JsonProperty Attribute修改返回 json 值的name 本例使用JsonPropertyAttribute在序列化为JSON时更改属性的名称。 排序 在反序列化期间使用的Required,以验证是否存在所需的JSON属性 JsonIgnoreAttribute 使用Json ......

使用jsonproperty attribute修改返回 json 值的name

本例使用jsonpropertyattribute在序列化为json时更改属性的名称。

public class videogame
{
    [jsonproperty("name")]
    public string name { get; set; }

    [jsonproperty("release_date")]
    public datetime releasedate { get; set; }
}
videogame starcraft = new videogame
{
    name = "starcraft",
    releasedate = new datetime(1998, 1, 1)
};

string json = jsonconvert.serializeobject(starcraft, formatting.indented);

console.writeline(json);
// {
//   "name": "starcraft",
//   "release_date": "1998-01-01t00:00:00"
// }

排序

public class account
{
    public string emailaddress { get; set; }

    // appear last
    [jsonproperty(order = 1)]
    public bool deleted { get; set; }

    [jsonproperty(order = 2)]
    public datetime deleteddate { get; set; }

    public datetime createddate { get; set; }
    public datetime updateddate { get; set; }

    // appear first
    [jsonproperty(order = -2)]
    public string fullname { get; set; }
}
account account = new account
{
    fullname = "aaron account",
    emailaddress = "aaron@example.com",
    deleted = true,
    deleteddate = new datetime(2013, 1, 25),
    updateddate = new datetime(2013, 1, 25),
    createddate = new datetime(2010, 10, 1)
};

string json = jsonconvert.serializeobject(account, formatting.indented);

console.writeline(json);
// {
//   "fullname": "aaron account",
//   "emailaddress": "aaron@example.com",
//   "createddate": "2010-10-01t00:00:00",
//   "updateddate": "2013-01-25t00:00:00",
//   "deleted": true,
//   "deleteddate": "2013-01-25t00:00:00"
// }

在反序列化期间使用的required,以验证是否存在所需的json属性

public class videogame
{
    [jsonproperty(required = required.always)]
    public string name { get; set; }

    [jsonproperty(required = required.allownull)]
    public datetime? releasedate { get; set; }
}
string json = @"{
  'name': 'starcraft iii',
  'releasedate': null
}";

videogame starcraft = jsonconvert.deserializeobject<videogame>(json);

console.writeline(starcraft.name);
// starcraft iii

console.writeline(starcraft.releasedate);
// null

jsonignoreattribute

使用jsonignoreattribute从序列化中排除属性

public class account
{
    public string fullname { get; set; }
    public string emailaddress { get; set; }

    [jsonignore]
    public string passwordhash { get; set; }
}

详情请参考 https://www.newtonsoft.com/json/help/html/jsonpropertyname.htm