将json转换为对象的c列表

本文关键字:列表 对象 json 转换 | 更新日期: 2023-09-27 18:24:09

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。我是不是错过了什么?

将json转换为对象的c列表

您的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);
        }
}

如果你想匹配C#结构,你可以像这样更改JSON字符串:

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