C#C
C#17mo ago
37 replies
RobG66

Issue with JSON serialization of a nested dictionary

I can update the allMediaSource nested dictionary fine and vs2022 debug shows it has new values, but when I serialize the nested dictionary, it has original values
Dictionary<string, Dictionary<string, Dictionary<string, string>>> allMediaSources = new Dictionary<string, Dictionary<string, Dictionary<string, string>>>();
string jsonString = Properties.Settings.Default.MediaSources;

if (!string.IsNullOrEmpty(jsonString))
{
    try
    {
        // Deserialize the JSON string into the nested dictionary structure
        allMediaSources = JsonSerializer.Deserialize<Dictionary<string, Dictionary<string, Dictionary<string, string>>>>(jsonString)
        ?? new Dictionary<string, Dictionary<string, Dictionary<string, string>>>(); // Ensure a non-null dictionary
    }
    catch (Exception ex)
    {
        // Handle deserialization errors (optional logging or handling)
        // For now, we'll just fall back to an empty dictionary
        allMediaSources = new Dictionary<string, Dictionary<string, Dictionary<string, string>>>();
    }
}


// Ensure that the scraper key exists in allMediaSources
if (!allMediaSources.ContainsKey(scraper))
{
    allMediaSources[scraper] = new Dictionary<string, Dictionary<string, string>>();
}

string newJsonString;

// Get the nested dictionary for the scraper
var nestedDictionary = allMediaSources[scraper];

// Check if the system key exists within the scraper's nested dictionary
if (!nestedDictionary.ContainsKey(system))
{
    // If the system key doesn't exist, add the mediaSources dictionary
    nestedDictionary.Add(system, mediaSources);
}
else
{
    // If the system key exists, replace the existing dictionary with mediaSources
    nestedDictionary[system] = mediaSources;
}

// Update property value            
newJsonString = JsonSerializer.Serialize(allMediaSources);
Properties.Settings.Default.MediaSources = newJsonString;

// Save the changes to the settings
Properties.Settings.Default.Save();
Was this page helpful?