使用JsonProperty Attribute修改返回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

转载于:https://www.cnblogs.com/WNpursue/p/10755011.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值