简体   繁体   中英

JSON to object using C# JavaScriptSerializer

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 .

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM