C#C
C#3y ago
Kyede

❔ Implement New Class to JSON with Default Values

Hello,

I have a class as followed:
        public class CommandModuleRoot
        {
            public List<GuildModulesConfiguration> GuildModulesConfiguration { get; set; }
        }

        public class GuildModulesConfiguration
        {
            public ModuleCaseSystem ModuleCaseSystem { get; set; }
        }

        public class ModuleCaseSystem
        {
            public int ModuleID { get; set; }
            public string ModuleName { get; set; }
            public bool ModuleIsActive{ get; set; }

            [Description("Sets the channel where cases are automatically or manually created regardless in which channel the command was executed in.")]
            public ulong GuildAutoPostChannel { get; set; }

            [Description("Determines whether the user will be notified about any cases created for them. This also includes modifications to the case such as updates.")]
            public bool EnableUserCaseNotifications { get; set; }
        }

Which returns:
{
  "ModuleCaseSystem": {
    "ModuleID": 1,
    "ModuleName": "CaseSystem",
    "ModuleIsActive": false,
    "GuildAutoPostChannel": 0,
    "EnableUserCaseNotifications": false
  }
}


Now, let's say I add a new class to GuildModulesConfiguration which would looks like this:
        public class GuildModulesConfiguration
        {
            public ModuleCaseSystem ModuleCaseSystem { get; set; }
            public NewModuleTest NewModuleTest { get; set; }
        }
        
        public class NewModuleTest
        {
            public int ModuleID { get; set; } = 2;
            public string ModuleName { get; set; } = "Test";
            public bool ModuleIsActive { get; set; } = false;
        }


Whenever I try to deserialize and serialize the JSON file, it adds the new class as null without any values.

{
  "ModuleCaseSystem": {
    "ModuleID": 1,
    "ModuleName": "CaseSystem",
    "ModuleIsActive": false,
    "GuildAutoPostChannel": 0,
    "EnableUserCaseNotifications": false
  },
  "NewModuleTest": null
}


What I want to achieve is this:
{
  "ModuleCaseSystem": {
    "ModuleID": 1,
    "ModuleName": "CaseSystem",
    "ModuleIsActive": false,
    "GuildAutoPostChannel": 0,
    "EnableUserCaseNotifications": false
  },
  "NewModuleTest": {
    "ModuleID": 2,
    "ModuleName": "Test",
    "ModuleIsActive": true
  }
}


Any ideas what I could possibly do? CryingMan
Was this page helpful?