一尘不染

将json转换为c#对象列表

json

Json字符串:

{"movies":[{"id":"1","title":"Sherlock"},{"id":"2","title":"The Matrix"}]}

C#类:

public class Movie {
  public string title { get; set; }
}

C#将json转换为电影的c#列表:

JavaScriptSerializer jss = new JavaScriptSerializer();
List<Movie> movies = jss.Deserialize<List<Movie>>(jsonString);

我的movies变量最终是一个计数为0的空列表。我是否缺少某些内容?


阅读 362

收藏
2020-07-27

共1个答案

一尘不染

您的C#类映射与json结构不匹配。

解决方案:

class MovieCollection {
        public IEnumerable<Movie> movies { get; set; }
}

class Movie {
        public string title { get; set; }
}

class Program {
        static void Main(string[] args)
        {
                string jsonString = @"{""movies"":[{""id"":""1"",""title"":""Sherlock""},{""id"":""2"",""title"":""The Matrix""}]}";
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                MovieCollection collection = serializer.Deserialize<MovieCollection>(jsonString);
        }
}
2020-07-27