convert json to c# list of objects

前端 未结 2 1655
野趣味
野趣味 2020-12-09 19:53

Json string:

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

C# class:

public          


        
相关标签:
2条回答
  • 2020-12-09 20:21

    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);
            }
    }
    
    0 讨论(0)
  • 2020-12-09 20:28

    If you want to match the C# structure, you can change the JSON string like this:

    {[{"id":"1","title":"Sherlock"},{"id":"2","title":"The Matrix"}]}
    
    0 讨论(0)
提交回复
热议问题