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

posted @ 2019-04-23 10:40  Pursue`  阅读(1170)  评论(0编辑  收藏  举报