Let me start by saying I am really new to C# and code in general so if anything I sloppy I apologize. I currently have a Json file named Database.json
containing:
{
"QAlist": {
"1u002B1": "2",
"2u002B2": "4"
}
}
I want to be able to Read the file converting it to a string and then deserialize the string into a variable that i can then display the elements, keys or values of.
So far i have this code:
namespace Createfile
{
public class QAcast
{
public Dictionary<string, string>? QAlist { get; set; }
}
class Program
{
static void Main(string[] args)
{
string filename = "./Database.json";
string fileread = File.ReadAllText(filename);
QAcast QAlist = JsonSerializer.Deserialize<QAcast>(fileread);
Console.WriteLine(QAlist);
}
}
}
The current output of this is: Createfile.QAcast
Where I would like it to be {"QAlist": {"1u002B1": "2", "2u002B2": "4"}}
or something of the like. Any help?
2
Answers
I tested it, everything deserialized properly. But Console.WriteLine can produce some strange result if you try to display the whole object instance. It uses ToString() implicitly and in many cases it just returns a full class name. Maybe you have to display items using this code
output
or if you just want to check deserialization, you can serialize the object you got again
output
When you call
Console.WriteLine(QAlist);
, it appears that the program prints the type name to the console. This is the default behavior for most types. Since every type in C# inherits from the Object class, every type also has access to theToString()
method. See here.ToString()
is being called on your behalf when you passQAList
toConsole.WriteLine()
. If you want to control how your data is printed, you can override theToString()
method to have some custom logic that will display your data in the console.Your
QAList
property is of typeDictionary<string, string>
. Simply loop over the key value pairs in your Dictionary then format the data for however you want it to appear in the console.Something like: