用JSON.NET序列化对象的属性/字段的特定属性

本文关键字:属性 字段 JSON 序列化 对象 NET | 更新日期: 2023-09-27 18:01:24

假设我有这两个类Book

public class Book
{
    [JsonProperty("author")]
    [---> annotation <---]
    public Person Author { get; }
    [JsonProperty("issueNo")]
    public int IssueNumber { get; }
    [JsonProperty("released")]
    public DateTime ReleaseDate { get; }
   // other properties
}

Person

public class Person
{
    public long Id { get; }
    public string Name { get; }
    public string Country { get; }
   // other properties
}

我想将Book类序列化为JSON,而不是将属性Author序列化为整个Person类,我只需要Person的Name在JSON中,所以它应该看起来像这样:

{
    "author": "Charles Dickens",
    "issueNo": 5,
    "released": "15.07.2003T00:00:00",
    // other properties
}

我知道有两种方法可以做到这一点:

  1. Book类中定义另一个名为AuthorName的属性,并只序列化该属性。
  2. 创建自定义JsonConverter,其中只指定特定的属性。

以上两个选项对我来说似乎都是不必要的开销,所以我想问是否有更简单/更短的方法来指定要序列化的Person对象的属性(例如注释)?

提前感谢!

用JSON.NET序列化对象的属性/字段的特定属性

序列化string而不是使用另一个属性序列化Person:

public class Book
{
    [JsonIgnore]
    public Person Author { get; private set; } // we need setter to deserialize
    [JsonProperty("author")]
    private string AuthorName // can be private
    {
        get { return Author?.Name; } // null check
        set { Author = new Author { Name = value }; }
    }
}