'Multiple objects serialization

I am making a ToDoList-Console app that needs serialisation of multiple objects. There are 2 task classes:

  • Simple task
  • Complex task

I need a method that serialises and desirealize these tasks, something like WriteAndReadComplexTask, for both the classes that does not rewrite the whole tasks.json file, but adds it up. This is what I am aiming for as an end result:

[
 {
    "SimpleTask": "do the dishes"
 }
 {
    "ComplexTask": "buy groceries"
      { "subtask": "bananas",
        "subtask": "apples"}
 }
 {
    "simple task": "do some coding"
 }
]


Solution 1:[1]

This isn't too hard to do. But I think you are approaching the problem from a different angle I suggest you try getting this to work with just 1 class which contains all fields already and using 1 todoitem task. This saves time and complex logic because otherwise you might need to convert items from simple tasks to complex tasks in the future.

  1. First of all, your JSON is still not correct. you are missing comma's after each object.

  2. I suggest changing your JSON to the following:

[
     {
        "name": "SimpleTask"
        "description": "do the dishes"
     },
     {
        "name": "Simple task",
        "description": "buy groceries",
         "subtasks":[ 
             {"name": "Simple task",
        "description": "buy groceries"},{.... repeat another item}]
     },
     {
         ..another item here 
     }
]
  1. Create a new class where which looks like the object in your JSON like this:
public class TodoItem 
{
    public string name {get;set;}
    public string description {get;set;}
    public List<TodoItem> subtasks {get;set;}
}
  1. Now in your code load the file and use the following to load to C#
var todoitems = JsonSerializer.Deserialize<List<TodoItem>>(jsonString);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1