skip to Main Content

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


  1. 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

    foreach (var item in QAlist.QAlist)
    {
        Console.WriteLine(item.Key + " = " + item.Value);
    }
    

    output

    1+1 = 2
    2+2 = 4
    

    or if you just want to check deserialization, you can serialize the object you got again

    Console.WriteLine(JsonConvert.SerializeObject(QAlist));
    

    output

    {"QAlist":{"1+1":"2","2+2":"4"}}
    
    Login or Signup to reply.
  2. 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 the ToString() method. See here.

    ToString() is being called on your behalf when you pass QAList to Console.WriteLine(). If you want to control how your data is printed, you can override the ToString() method to have some custom logic that will display your data in the console.

    Your QAList property is of type Dictionary<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:

    public class QAcast
    {
        public Dictionary<string, string>? QAlist { get; set; }
    
        public override string ToString()
        {
            string result = "{";
            foreach (var entry in QAlist)
            {
                result += $"{entry.Key}: {entry.Value}, ";
            }
            return result += "}";
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search