将json转换为c#对象列表

时间:2012-02-13 02:36:02

标签: c# json javascriptserializer

Json string:

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

C#class:

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

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

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

我的movies变量最终是一个空数列表,其中count = 0.我错过了什么?

2 个答案:

答案 0 :(得分:20)

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

答案 1 :(得分:0)

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

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