Click here to Skip to main content
15,668,842 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I tried to add a dictionary after load a file (JSON). However, it won't load, and I added it to the list I wanted to, but it won't work this way.

if (File.Exists(fileName))
            StreamReader sr = new StreamReader(fileName);
            string json = sr.ReadToEnd();
            Dog dog = JsonConvert.DeserializeObject<Dog>(json);
            Console.WriteLine("File loaded");

void ListAllDogs()
    Console.WriteLine("LIST OF DOGS");
    // check if there is any dog in the list
    if (dogs.Count == 0)
        Console.WriteLine("There is no dog in the list");
        foreach (KeyValuePair<string, Dog> dog in dogs)

Another problem also the needs to remove a null in the JSON after writing a file. Therefore, I need to convert from list to the string in the JSON. I am currently using Newtonsoft.Json.

Console.Write("Enter the dog's vaccine: ");
            string vaccine = Console.ReadLine();
            if (vaccine == "")
                Console.WriteLine("Please enter a valid vaccine");
            StreamWriter sw = new StreamWriter(fileName);
            sw.WriteLine(JsonConvert.SerializeObject(new Dog(name, breed, age, vaccine)));
            Console.WriteLine("File written");

What I have tried:

I have tried to set
dogs.Add(dog.Name, dog)
, which is an add to the dictionary after loaded it. Another solution that was not working when I tried to do this
dogs = JsonConvert.DeserializeObject<Dictionary<string, Dog>>(json);

All are not working, so I am trying to figure out how to remove a null since the vaccine is a list (not a dictionary, and I have added a List in the Program.cs included a class for private & public properties). Then, I also need to figure it how to load into a list for show dog info.

On the next issue, I mentioned about null in the JSON after I typed in an input. I have tried to use different ways, especially this one:
it actually shows
however when I try to load this to the list (i am using a dictionary to show) while used
<pre> StreamReader sr = new StreamReader(fileName);
            string json = sr.ReadToEnd();
            dogs = JsonConvert.DeserializeObject<Dictionary<string, Dog>>(json);
            // Dog dog = JsonConvert.DeserializeObject<Dog>(json);
            // string rawJson = File.ReadAllText(fileName);
            // Dog dog = JsonConvert.DeserializeObject<Dog>(json);
            Console.WriteLine("File loaded");
the error messages shown or display no dogs when check list (when use different ones such as JsonConvert.DeserializeObject)
Updated 29-Nov-22 17:14pm
Richard Deeming 30-Nov-22 4:40am    

Why?! You already have the JsonConvert class to deserialize JSON; why would you not also use that class to serialize the JSON? Doing anything else will result in corrupt / invalid JSON which you can't deserialize.

1 solution

Your first issue is that the JSON above is a single object, not a collection of objects. Json collections are surrounded in square brackets. So Your JSON should be:
	"Name": "Lea",
	"Breed": "German",
	"Age": 17,
	"Vaccines": null

When deserializing JSON data, it is best to define classes to deserialize into. I use JSON Utils: Generate C#, VB.Net, SQL TAble and Java from JSON[^]. Here is the output from your JSON above:
public class Dog
	public string Name { get; set; }

	public string Breed { get; set; }

	public int Age { get; set; }

	public string Vaccines { get; set; }

Next, for small JSON files/data you don't need to use streams:
string rawJson = File.ReadAllText("dog.json");
Dog dog = JsonConvert.DeserializeObject<Dog>(rawJson);

But if you want to use Stream, then you would do something like this:
using Stream stream = File.OpenRead("dog.json");

// set up the stream readers
using TextReader textReader = new StreamReader(stream);
using JsonReader jsonReader = new JsonTextReader(textReader);

JsonSerializer serializer = new();

Dog dog = serializer.Deserialize<Dog>(jsonReader);

I have written comprehensive articles on these subjects. If you want to know more, here are two that cover NewtonSoft:
* Working with Newtonsoft.Json in C# & VB[^]
* Deserializing Json Streams using Newtonsoft.Json & System.Text.Json with C# & VB[^]

Hope this helps!
Share this answer
stybjs 29-Nov-22 22:57pm    
I will try that and test if it works because it is my first time to use json file for C#.
stybjs 29-Nov-22 23:00pm    
And how will it works if I use JSON property on this
private List<string> vaccines;
    public List<string> Vaccines
        get { return vaccines; }
        set { vaccines = value; }
Graeme_Grant 29-Nov-22 23:31pm    
Depends on the JSON data. use the JSON Utils: Generate C#, VB.Net, SQL TAble and Java from JSON[^] with your raw JSON data to generate the classes. That is what I did with your data.
stybjs 29-Nov-22 23:07pm    
I can't seem to edit my comment. Anyways, I need to fix a null in the JSON because the vaccine is a list, so it needs to change a string, or I am not sure, but I need to see a vaccine name that I typed in an input and then load it into a list (dictionary when I chose to list dog info in menu selection).
Graeme_Grant 29-Nov-22 23:17pm    
I gave you the JsonUtil tool website and the how-to. I have also given you links to articles that cover this and more in great detail. You need a JSON sample of what that structure is. This is an exercise for you...

Also, if you want to edit your "reply", use the pencil on the right next to the red X.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900