I am attempting to learn how to use JSON Serialization to save an object to disk, but I am running into an issue when the object I want to serialize has other objects within it.
If use the following:
string output = JsonConvert.SerializeObject(CharacterRepository);
The CharacterRepository will be serialized, the List of CharacterRecords will be serialized, but the CharacterINI data inside the CharacterRecord will be invalid. When I used BitFormatter this was not an issue, so I am hoping someone would help me understand the proper way to use JSON Serialization to save my object.
My current (working) code below that uses BinaryFormatter...
CharacterINI class
[Serializable]
internal class CharacterINI
{
internal readonly string FilePath = string.Empty;
internal Dictionary<string, Dictionary<string, string>> RAWDATA { get; private set; } = new();
internal Dictionary<string, string> Panels...
internal Dictionary<string, string> Macros...
internal Dictionary<string, string> Chat...
internal Dictionary<string, string> NameOptions...
internal Dictionary<string, string> QuickBinds...
internal Dictionary<string, string> ToolTips...
public CharacterINI(string filepath)...
[...]
}
CharacterRecord class
[Serializable]
internal class CharacterRecord
{
public string? Name...
public string? Realm...
public string? Class...
public string? Description...
public CharacterINI? characterINI...
public string? Server...
public int Index...
}
RecordRepository class
[Serializable]
internal class RecordRepository
{
public List<CharacterRecord>? Characters...
public int Count => Characters?.Count??-1;
public bool Contains(string name) => Characters?.Where(x => x.Name == name).Count() > 0;
}
This is where I perform the serialization and save the object to disk
{
CharacterINI characterIniData = new CharacterINI(characterPath);
[...]
var characterRecord = new CharacterRecord
{
Name = BackUpNameComboBox.Text,
Realm = BackUpRealmComboBox.Text,
Class = BackUpClassComboBox.Text,
Description = BackUpDescriptionTextBox.Text,
characterINI = characterIniData,
Server = BackUpServerTextBox.Text,
Index = (recordCount == 0) ? 0 : recordCount
};
CharacterRepository.Characters.Add(characterRecord); //CharacterRepository is type RecordRepository
using (Stream stream = File.Open(RespositryFullPath, FileMode.Create))
{
var binaryFormatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
binaryFormatter.Serialize(stream, CharacterRepository);
}
[...]
}