It seems that if an object is an IEnumerable
, Json ignores its fields and serialise the enumerable. For example, for a class like below, Title
is not serialised. I have found almost the same question, and the answer was adding [JsonObject]
to the class, but it was about using Newtonsoft.Json, and I am using .NET 7.0's Json via JsonResult
. Is there something equivalent for .NET Json?
var myBook = new Book()
{
Title = "Jane Eyre",
Pages = new List<string>() { "page1", "page2", "page3" }
};
var options = new JsonSerializerOptions { IncludeFields = true };
return new JsonResult(myBook, options);
}
public class Book:IEnumerable<string>
{
public string Title;
public IList<string> Pages;
public IEnumerator<string> GetEnumerator()
{
return Pages.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return Pages.GetEnumerator() as IEnumerator;
}
}