6

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.

Luke T O'Brien
  • 2,565
  • 3
  • 26
  • 38
  • 4
    The serializer serializes properties. – Ralf Nov 30 '20 at 17:11
  • 5
    `However, the C# object most definitely do have properties with the correctly entered values.`, I would disagree. That class doesn't contain properties, those are public fields. – Trevor Nov 30 '20 at 17:14
  • 1
    https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-5-0#include-fields – Crowcoder Nov 30 '20 at 17:14
  • Thanks, I should of spotted that! – Luke T O'Brien Nov 30 '20 at 17:15
  • 1
    This shouldn't be flagged as a duplicate in .NET 5 (and I am voting to reopen the question). As of .NET 5, a setting can be flagged to allow for the serialization of fields. https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to?pivots=dotnet-5-0#include-fields – David L Nov 30 '20 at 17:56

1 Answers1

8

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);
David L
  • 32,885
  • 8
  • 62
  • 93