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.

3
  • Did you try like this? string json = "[{\"title\": \"Something\",\"year\": \"1999\",\"releaseDate\": \"1234\"},{\"title\": \"Something2\",\"year\": \"1992\",\"releaseDate\": \"1235\"}]"; Commented Jan 21, 2015 at 0:16
  • Not exactly like that, but I did try with only one movie with {}. Commented Jan 21, 2015 at 0:21
  • Any reason why you can't use JSON.NET by Newtonsoft? Commented Jan 21, 2015 at 10:02

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

2 Comments

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):
You shouldn't be using fields for your JSON DTOs. You should NEVER have public fields. Use properties instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.