简体   繁体   中英

convert json to c# list of objects

Json string:

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

C# class:

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

C# converting json to c# list of Movie's:

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

My movies variable is ending up being an empty list with count = 0. Am I missing something?

Your c# class mapping doesn't match with json structure.

Solution :

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"}]}

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