Home > Mobile >  Deserialize Json string with child objects
Deserialize Json string with child objects

Time:04-19

Got the following structure given:

public class TaskList
{
    public string Name { get; set; }
    public List<ToDoTask> ToDoTasks { get; set; }
}

public class ToDoTask
{
    public string Name { get; set; }
    public string Note { get; set; }
    public DateTime LastEdit { get; set; }
    public bool Finished { get; set; }
}

I'm using System.Text.Json in .NET 5.0 to serialize a List successfully into a json-file:

JsonSerializerOptions serializeOptions = new() { WriteIndented = true };
string json = JsonSerializer.Serialize(taskLists, serializeOptions);

the result looks fine:

{
  "TaskLists": [
    {
      "Name": "List1",
      "ToDoTasks": [
        {
          "Name": "Task1",
          "Note": "",
          "LastEdit": "2022-04-19T13:05:10.0415588 02:00",
          "Finished": false
        },
        {
          "Name": "Task2",
          "Note": "",
          "LastEdit": "2022-04-19T13:05:13.9269202 02:00",
          "Finished": false
        }
      ]
    },
    {
      "Name": "List2",
      "ToDoTasks": [
        {
          "Name": "Task3",
          "Note": "",
          "LastEdit": "2022-04-19T13:05:18.3989081 02:00",
          "Finished": false
        },
        {
          "Name": "Task4",
          "Note": "",
          "LastEdit": "2022-04-19T13:05:23.0949034 02:00",
          "Finished": false
        }
      ]
    }
  ]
}

When I deserialize this json-file, I only got the TaskLists but the ToDoTasks, are empty.

List<TaskList> taskLists = JsonSerializer.Deserialize<List<TaskList>>(json);

What do I have to do, get also the ToDoTask-Childs included into the deserialized objects?

CodePudding user response:

Whenever you cannot figure out your model class, you can use Visual Studio's Edit - Paste Special - Paste JSON as Class to check out.

Your model classes should be like this:

public class Rootobject
{
    public Tasklist[] TaskLists { get; set; }
}

public class Tasklist
{
    public string Name { get; set; }
    public Todotask[] ToDoTasks { get; set; }
}

public class Todotask
{
    public string Name { get; set; }
    public string Note { get; set; }
    public DateTime LastEdit { get; set; }
    public bool Finished { get; set; }
}

And you can Deserialize it:

static void Main(string[] args)
{
    var query = JsonSerializer.Deserialize<Rootobject>(File.ReadAllText("data.json"));
}

CodePudding user response:

Your json has a root object containing the task list, so List<TaskList> does not represent it correctly. Try:

public class Root
{
    public List<TaskList> TaskLists { get; set; }
}

var root = JsonSerializer.Deserialize<Root>(json);
  • Related