Luke T O'Brien
Luke T O'Brien

Reputation: 2845

System.Text.Json not serialising List<T>

I am just .Net 5.

I am creating a QC app with Blazor and I am using System.Text.Json to serialise a wrapper object that has a property of List<T> which are answers to QC questions that are post to the server and saved in the database.
However each item in the List is not being serialised, so the posted request has a empty List .

So in my code I am just doing a very simple serialisation of an object:

string content = JsonSerializer.Serialize(obj);

If I debug then I can see the Answers array has the correct length, but every item is empty:
'{"Answers":[{},{},{},{}],...}'
However, the C# object most definitely do have properties with the correctly entered values.

The T is an answer object, it is just a POCO with not annotation:

    public class ReturnedQCResult
    {
        public string Question;
        public int QuestionEntryTypeID;
        public char QuestionType;
        public short QuestionSequence;
        public string Text;
        public decimal? Number;
        public bool? YesNo;
        public DateTime? DateEntry;
        public TimeSpan? TimeEntry;
        public long QuestionID;
    }

Does anyone have any idea as to why this is happening or if there is a setting to turn on?

Many thanks.

Upvotes: 7

Views: 8948

Answers (1)

David L
David L

Reputation: 33833

While previous versions of System.Text.Json could only serialize public properties, as of .NET 5, you can now explicitly tell System.Text.Json to include fields in serialization: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-5-0#include-fields

var options = new JsonSerializerOptions()
{
    IncludeFields = true,
};
string content = JsonSerializer.Serialize(obj, options);

Upvotes: 12

Related Questions