I have existing third party DLL - which has several classes. I don't have source code of this DLL. Lets assume that it has Book class defined as below
public class Book
{
public String Id { get; set; }
public String Title { get; set; }
public String Author{ get; set; }
public List<Page> Pages { get; set; }
}
I have created Asp.net Core Web API project and referred DLL and wrote API Controller for GET method of http.
[HttpGet("{id}")]
public ActionResult<Book> Get(string id)
{
Book b = Book.FindById(id); // This utility function returns Book instance.
return Ok(b);
}
My requirement is return value of JSON should be something like
{
"id" : "1234",
"Title" : "How to Custom Serialize JSON",
"Author" : "Myself",
"NumberOfPages" : 100
}
So basically, whenever JSON serialization happens, I want to ensure that Pages attribute is not serialized as it has many complications. But I should able to add new attribute NumberOfPages. Basically I want to take control of Serialization. I have seen many examples but I could not find this particular case where I want to custom serialize existing class.
I am not worrying about deserialization right now.
I can see that serialization starts from
Microsoft.AspNetCore.Mvc.Formatters.JsonOutputFormatter.WriteObject(TextWriter writer, Object value)
return Ok(new { b.Id, b.Title, b.Author, NumberOfPages = b.Pages.Count});?