C
C#11mo ago
Mekasu0124

✅ Working With Json

public static bool CreateJsonFile()
{
Dictionary<string, bool> newDict = new Dictionary<string, bool>();
newDict.Add("agree", false);

var jsonData = JsonSerializer.Serialize(newDict);

try
{
File.WriteAllText(_jsonFile, jsonData);
return true;
}
catch (Exception ex)
{
ColorPrint.WriteLine(ex.Message, ConsoleColor.Red);
return false;
}
}
public static bool CreateJsonFile()
{
Dictionary<string, bool> newDict = new Dictionary<string, bool>();
newDict.Add("agree", false);

var jsonData = JsonSerializer.Serialize(newDict);

try
{
File.WriteAllText(_jsonFile, jsonData);
return true;
}
catch (Exception ex)
{
ColorPrint.WriteLine(ex.Message, ConsoleColor.Red);
return false;
}
}
this current code creates a json file that looks simply like
{"agree": false}
{"agree": false}
however I want to add two new values to it so that it looks like
{
"agree": false,
"username": "",
"password": ""
}
{
"agree": false,
"username": "",
"password": ""
}
but I'm not sure how to edit the current code. Thanks
5 Replies
Mekasu0124
Mekasu0124OP11mo ago
Do I need to create a second dictionary?
Jimmacle
Jimmacle11mo ago
i don't recommend using a dictionary, define a class that holds your data and serialize that
Mekasu0124
Mekasu0124OP11mo ago
so like a model? like
public class SetupModel
{
public bool Setup { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}

//in setup function

public static bool SetupJson ()
{
SetupModel setup = new()
{
Setup = false,
Username = "",
Password = ""
}

// serialize json
// file . write all text
}
public class SetupModel
{
public bool Setup { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}

//in setup function

public static bool SetupJson ()
{
SetupModel setup = new()
{
Setup = false,
Username = "",
Password = ""
}

// serialize json
// file . write all text
}
like that?
Jimmacle
Jimmacle11mo ago
yep
Mekasu0124
Mekasu0124OP11mo ago
bet tyvm
Want results from more Discord servers?
Add your server