将json转换为c#对象列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9254887/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
convert json to c# list of objects
提问by Ian Davis
Json string:
JSON字符串:
{"movies":[{"id":"1","title":"Sherlock"},{"id":"2","title":"The Matrix"}]}
C# class:
C# 类:
public class Movie {
public string title { get; set; }
}
C# converting json to c# list of Movie's:
C# 将 json 转换为 C# 电影列表:
JavaScriptSerializer jss = new JavaScriptSerializer();
List<Movie> movies = jss.Deserialize<List<Movie>>(jsonString);
My moviesvariable is ending up being an empty list with count = 0. Am I missing something?
我的movies变量最终是一个 count = 0 的空列表。我错过了什么吗?
采纳答案by Khairuddin Ni'am
Your c# class mapping doesn't match with json structure.
您的 c# 类映射与 json 结构不匹配。
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);
}
}
回答by ToddZhao
If you want to match the C# structure, you can change the JSON string like this:
如果要匹配 C# 结构,可以像这样更改 JSON 字符串:
{[{"id":"1","title":"Sherlock"},{"id":"2","title":"The Matrix"}]}

