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

限于喜欢 提交于 2020-01-25 22:05:01

问题


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:

  1. To define another property in Book class called AuthorName and serialize only that property.
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!