Search code examples
c#jsonjson-deserializationsystem.text.json

Deserialize JSON into an Object(s) using System.Text.Json


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)


Solution

  • 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
    };