簡體   English   中英

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

[英]Serialize specific property of object's property/field with JSON.NET

假設我有這兩個類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對象的屬性(例如注釋)?

提前致謝!

序列化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 }; }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM