C
C#2mo ago
intee_

✅ Deserialize JSON back into custom object

Hey all, I have an ObservableCollection that I am using to store a list of tasks (A custom object "TaskItem" that is build like this.
c#

internal class TaskItem {

public string Task { get; set; }
public string Description { get; set; }
public string Date { get; }

public TaskItem()
{
Date = DateTime.Now.ToString("hh:mmtt dd/MMM/yyyy");
}
}
c#

internal class TaskItem {

public string Task { get; set; }
public string Description { get; set; }
public string Date { get; }

public TaskItem()
{
Date = DateTime.Now.ToString("hh:mmtt dd/MMM/yyyy");
}
}
And in my ViewModel I'm creating an ObservableCollection of those item types, called "TaskList". I am exporting that list of TaskItems to Json and that works fine with the below:
c#
string json = JsonConvert.SerializeObject(TaskList);
File.WriteAllText(SavePath, json)
c#
string json = JsonConvert.SerializeObject(TaskList);
File.WriteAllText(SavePath, json)
But I can't seem to work out how the hell I load that back into TaskList variable when I re-open the app. I have been messing around with this in the ViewModel constructor:
c#
string loadedJSON = File.ReadAllText(SavePath);
TaskList = JsonConvert.DeserializeObject<TaskItem>(loadedJSON);
c#
string loadedJSON = File.ReadAllText(SavePath);
TaskList = JsonConvert.DeserializeObject<TaskItem>(loadedJSON);
Trieda bunch of different stuff in there, this was just what I gave up on haha. Am I at least getting close? haha.
4 Replies
Kouhai
Kouhai2mo ago
You can just do JsonConvert.DeserializeObject<ObservableCollection<TaskItem>>(loadedJSON);
intee_
intee_2mo ago
Legend, thanks heaps mate! Is that going to create a new TaskList object or use the one that is being declared in the constructor above it? This is also in the constructor:
c#
TaskList = new ObservableCollection<TaskItem>();
c#
TaskList = new ObservableCollection<TaskItem>();
Oh, never mind. Got it! Thanks heaps mate, I never tried the <ObservableCollection<TaskItem>> I tried <ObservableCollection><TaskItem> -.-
Kouhai
Kouhai2mo ago
DeserializeObject<ObservableCollection<TaskItem>>(loadedJSON) will create a whole new ObservableCollection<TaskItem> and won't reuse the previously created collection :ThumbsUp:
intee_
intee_2mo ago
I just threw TaskList = on the front and it seems to be loading the json into my datagrid haha 😛
Want results from more Discord servers?
Add your server