[英]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
}
我知道兩個選擇如何實現這一目標:
Book
類中定義另一個名為AuthorName
屬性,並僅序列化該屬性。 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.