Click here to Skip to main content
15,867,308 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.

C#
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;
        }


C#
void ListAllDogs()
{
    Console.WriteLine("LIST OF DOGS");
    Console.WriteLine(DASHER);
    // check if there is any dog in the list
    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}

C#
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:
C#
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
C#
<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);
            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)
Posted
Updated 29-Nov-22 17:14pm
v3
Comments
Richard Deeming 30-Nov-22 4:40am    
sw.WriteLine($"{{\"name\":\"{name}\",\"breed\":\"{breed}\",\"age\":{age},\"vaccine\":[\"{vaccine}\"]}}");

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:
JavaScript
[{
	"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:
C#
public class Dog
{
	[JsonProperty("Name")]
	public string Name { get; set; }

	[JsonProperty("Breed")]
	public string Breed { get; set; }

	[JsonProperty("Age")]
	public int Age { get; set; }

	[JsonProperty("Vaccines")]
	public string Vaccines { get; set; }
}

Next, for small JSON files/data you don't need to use streams:
C#
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:
C#
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
 
v2
Comments
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