I have a JSON file named 'movies.json' which contains an object and an array of 3 movies. The JSON in movies.json looks like this:
{
"theMovies": [
{
"name": "Starship Troopers",
"year": 1997
},
{
"name": "Ace Ventura: When Nature Calls",
"year": 1995
},
{
"name": "Big",
"year": 1988
}
]
}
I also have a class named Movie
public class Movie
{
public string Name { get; set; }
public int Year { get; set; }
}
I am trying to read the file into a string and deserialize the JSON to a type of Movie like this:
Movie movie1 = JsonConvert.DeserializeObject<Movie>(File.ReadAllText(@"c:\Temp\movies.json"));
and like this:
using (StreamReader file = File.OpenText(@"c:\Temp\movies.json"))
{
JsonSerializer serializer = new JsonSerializer();
Movie movie2 = (Movie)serializer.Deserialize(file, typeof(Movie));
Console.WriteLine(movie2.Name);
Console.WriteLine(movie2.Year);
}
Neither one works. Both movie1 and movie2 show no real data the Watch window:
movie1.Name = null
movie1.Year = 0
movie2.Name = null
movie2.Year = 0
Apparently having an object with an array inside is not working. Any suggestions?
Movie[]) so that's what you need to deserialize to