0

I'm trying to create a list of Movies from a JSON-string fetched from an API (testing with a string-variable so far). My Movie-class:

private string title { get; set; }
private int year { get; set; }
private string releaseDate { get; set; }

public override String ToString()
{
    return title + " (" + year + "): " + releaseDate;
}

The code below however does not insert anything into the Movie-objects. A little time ago it created 2 objects (which is right because it's 2 movies in the JSON-string), but with no content what-so-ever. Now I'm stuck with nothing, the code does not create any objects.

string json = "{\"movies\": [{\"title\": \"Something\",\"year\": \"1999\",\"releaseDate\": \"1234\"},{\"title\": \"Something2\",\"year\": \"1992\",\"releaseDate\": \"1235\"}]}";

List<Movie> movieList = new JavaScriptSerializer().Deserialize<List<Movie>>(json);

It's obvious that I'm quite new to this, but I can't seem to find a solution to my problem elsewhere 'cause either it's not the same issue as I have or I can't find the difference between my code and the solution.

What am I missing here? Does the variable-names have to be the same in the Movie-class as in the JSON-string?

EDIT: I finally found my second problem here. Turns out it's wrong to write private when you use auto properties. Also see { get; set; } syntax.

Community
  • 1
  • 1
PWL
  • 456
  • 4
  • 27

1 Answers1

2

Your JSON is an object that contains a "movies" property that is an array:

{
    movies: [
        {
            "title": "Something"
        },
        {
            "title": "Something Else"
        }
    ]
}

To deserialize it, you need an object with a "movies" property like this:

class MoviesObject {
    public List<Movie> movies { get; set; }
}

List<Movie> movieList = new JavaScriptSerializer().
    Deserialize<MoviesObject>(json).movies;
Jason Goemaat
  • 28,692
  • 15
  • 86
  • 113
  • So I need an object that contains the outer list like in the JSON as well? Thanks so far, I have now 2 empty objects again. My output: `(0): (0):` – PWL Jan 21 '15 at 00:25
  • You shouldn't be using fields for your JSON DTOs. You should NEVER have public fields. Use properties instead. – Aron Jan 21 '15 at 00:43