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);
sr.Close();
Console.WriteLine("File loaded");
break;
}
void ListAllDogs()
{
Console.WriteLine("LIST OF DOGS");
Console.WriteLine(DASHER);
if (dogs.Count == 0)
{
Console.WriteLine("There is no dog in the list");
}
else
{
foreach (KeyValuePair<string, Dog> dog in dogs)
{
Console.WriteLine(dog.Value);
}
}
}
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.
{"Name":"Lea","Breed":"German","Age":17,"Vaccines":null}
Console.Write("Enter the dog's vaccine: ");
string vaccine = Console.ReadLine();
if (vaccine == "")
{
Console.WriteLine("Please enter a valid vaccine");
continue;
}
StreamWriter sw = new StreamWriter(fileName);
sw.WriteLine(JsonConvert.SerializeObject(new Dog(name, breed, age, vaccine)));
sw.Close();
Console.WriteLine("File written");
break;
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:
sw.WriteLine($"{{\"name\":\"{name}\",\"breed\":\"{breed}\",\"age\":{age},\"vaccine\":[\"{vaccine}\"]}}");
it actually shows
{"name":"Brandon","breed":"German","age":18,"vaccine":["Flu"]}
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);
sr.Close();
Console.WriteLine("File loaded");
the error messages shown or display no dogs when check list (when use different ones such as JsonConvert.DeserializeObject)