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

时间:2021-07-27 22:49:45

Suppose I have these two classes Book

假设我有这两个类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
}

and Person

和人

public class Person
{
    public long Id { get; }

    public string Name { get; }

    public string Country { get; }

   // other properties
}

I want to serialize Book class to JSON, but instead of property Author serialized as whole Person class I only need Person's Name to be in JSON, so it should look like this:

我想将Book类序列化为JSON,但不是属性作为整个Person类序列化,我只需要Person的名称为JSON,所以它应该如下所示:

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

I know about two options how to achieve this:

我知道如何实现这两个选项:

  1. To define another property in Book class called AuthorName and serialize only that property.
  2. 要在Book类中定义名为AuthorName的另一个属性,并仅序列化该属性。
  3. To create custom JsonConverter where to specify only specific property.
  4. 要创建自定义JsonConverter,只在其中指定特定属性。

Both options above seem as an unnecessary overhead to me so I would like to ask if there is any easier/shorter way how to specify property of Person object to be serialized (e.g. annotation)?

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

Thanks in advance!

提前致谢!

1 个解决方案

#1


2  

Serialize string instead of serializing Person using another property:

序列化字符串而不是使用另一个属性序列化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 }; }
    }
}

#1


2  

Serialize string instead of serializing Person using another property:

序列化字符串而不是使用另一个属性序列化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 }; }
    }
}