0

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!

3
  • 1
    You could add another property of string type in getter of which you return Author.Name and in the setter create Person (using name given). Serialize that property instead (attribute it with JsonProperty("author")). Commented Aug 9, 2016 at 13:49
  • You could derive Book from Person and try public string Author { get { return this.Name; } } maybe? *Edit: Nvm, you don't want to serialize whole Person class anyways. Not deleting comment for sake of transparency :) Commented Aug 9, 2016 at 13:52
  • @Sinatr Thanks, that option crossed my mind but I want to avoid creating another single-purpose property because of that :P Commented Aug 9, 2016 at 13:55

1 Answer 1

2

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 }; }
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

why do you provide a setter for AuthorName?
@oldbam, for deserializer: author value is read from json as string, but we need Author (another property) value as Person. This is what setter of AuthorName is doing - constructing Person from string and assigning it to Author property.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.