6

I am trying to use the System.Text.Json.Serialization namespace to deserialize the text within a JSON file into an Object named Note, to then access its properties. With the later intent to read-in multiple Note objects, to then store in a List for example.

There don't seem to be many examples on the usage of this namespace, other than within the DOTNET docs https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to

This is my attempt based on the examples given. Which throws the error shown below, if you know what I'm doing wrong please let me know, thanks.

class Note
{
    public DateTime currentDate { get; set; }
    public string summary { get; set; }
    public Note(DateTime _date, string _sum)
    {
        currentDate = _date;
        summary = _sum;
    }
}

class Program
{
    static void Main(string[] args)
    {
        //Write json data
        string path = @"D:\Documents\Projects\Visual Projects\Notes Data\ThingsDone.json";

        DateTime date = DateTime.Now;
        string givenNote = "summary text";

        Note completeNote = new Note(date, givenNote);

        string serialString = JsonSerializer.Serialize(completeNote);
        File.WriteAllText(path, serialString);

        //Read json data
        string jsonString = File.ReadAllText(path);
        Note results = JsonSerializer.Deserialize<Note>(jsonString);
        Console.WriteLine(results.summary);
    }
}

Also I've looked into Json.NET and other options, but I would rather use this one (if possible)

Luc
  • 67
  • 1
  • 1
  • 5
  • [tag:system.text.json] does not support deserializing objects with parameterized constructors, see [Exception parsing json with System.Text.Json.Serialization](https://stackoverflow.com/q/56486474/3744182). You will need to add a parameterless constructor. Beyond that we need to see the JSON you are trying to deserialize -- i.e. a [mcve]. – dbc May 03 '20 at 13:27
  • Probably, you need to provide parameterless constructor, even private to your Note class – Konstantin Nikolskii May 03 '20 at 13:28

1 Answers1

2

Your Note class needs a parameterless constructor

class Note
{
    public DateTime currentDate { get; set; }
    public string summary { get; set; }

    // add this
    public Note()
    {
    }

    public Note(DateTime _date, string _sum)
    {
        currentDate = _date;
        summary = _sum;
    }
}

It might be worth thinking if you need your original two parameter constructor. If you removed it, then you could instantiate a new Note like this

var completeNote = new Note
{
    currentdate = date,
    summary = givenNote
};
Kevin Brydon
  • 12,524
  • 8
  • 46
  • 76
  • In C# 9.0, you can use parameterized record with positional constructor i.e. `record Note(DateTime currentDate, string summary);` – TimTIM Wong Nov 21 '20 at 14:56