问题
Suppose I have these two classes 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:
{
"author": "Charles Dickens",
"issueNo": 5,
"released": "15.07.2003T00:00:00",
// other properties
}
I know about two options how to achieve this:
- To define another property in
Book
class calledAuthorName
and serialize only that property. - To create custom
JsonConverter
where to specify only specific property.
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)?
Thanks in advance!
回答1:
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 }; }
}
}
来源:https://stackoverflow.com/questions/38852500/serialize-specific-property-of-objects-property-field-with-json-net