简体   繁体   English

JSON使用C#JavaScriptSerializer进行对象

[英]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). 我正在尝试通过从API提取的JSON字符串创建电影列表(到目前为止测试了字符串变量)。 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. 但是,下面的代码不会在Movie对象中插入任何内容。 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. 不久前,它创建了2个对象(这是正确的,因为它是JSON字符串中的2部电影),但是却没有任何内容。 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? 电影类中的变量名称是否必须与JSON字符串中的变量名称相同?

EDIT: I finally found my second problem here . 编辑:我终于在这里找到了第二个问题。 Turns out it's wrong to write private when you use auto properties. 事实证明,使用自动属性时写私有是错误的。 Also see { get; 另请参阅{get; set; 组; } syntax . 语法

Your JSON is an object that contains a "movies" property that is an array: 您的JSON是一个对象,其中包含“电影”属性,该属性是一个数组:

{
    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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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