C
C#10mo 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
Mekasu012410mo ago
Do I need to create a second dictionary?
Jimmacle
Jimmacle10mo ago
i don't recommend using a dictionary, define a class that holds your data and serialize that
Mekasu0124
Mekasu012410mo 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
Jimmacle10mo ago
yep
Mekasu0124
Mekasu012410mo ago
bet tyvm
Want results from more Discord servers?
Add your server