问题描述
假设我有这两个类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中,因此它应该看起来像这样:
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:
{
"author": "Charles Dickens",
"issueNo": 5,
"released": "15.07.2003T00:00:00",
// other properties
}
我知道如何实现这一目标的两个选择:
I know about two options how to achieve this:
- 要在
Book
类中定义另一个名为AuthorName
的属性,并仅序列化该属性. - 在仅指定特定属性的地方创建自定义
JsonConverter
.
- To define another property in
Book
class calledAuthorName
and serialize only that property. - To create custom
JsonConverter
where to specify only specific property.
以上两个选项对我来说都是不必要的开销,所以我想问一下是否有任何更简便的方法来指定要序列化的Person
对象的属性(例如注释)?
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)?
提前谢谢!
推荐答案
序列化string
而不是使用另一个属性来序列化Person
:
Serialize string
instead of serializing Person
using another property:
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 }; }
}
}
这篇关于使用JSON.NET序列化对象的属性/字段的特定属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!