如何将JSON数组转换为List<>?

19
这是我的JSON,我需要访问出勤数组中每个对象下面的数值:
{"name":" ","course":"","attendance":[{"name":"INTERNATIONAL FINANCE","type":"Theory","conducted":"55","present":"50"},{"name":"INDIAN CONSTITUTION","type":"Theory","conducted":"6","present":"6"}]}

这是我的代码:

public class Att
{

    public class Attendance
    {
        public string name { get; set; }
        public string type { get; set; }
        public string conducted { get; set; }
        public string present { get; set; }
    }


    public Att(string json)
    {
        JObject jObject = JObject.Parse(json);
        JToken jUser = jObject;

        name = (string)jUser["name"];
        course = (string)jUser["course"];
        attender = jUser["attendance"].ToList<Attendance>;

    }

    public string name { get; set; }
    public string course { get; set; }
    public string email { get; set; }
    //public Array attend { get; set; }

    public List<Attendance> attender { get; set; }
}

我有问题的是attender = jUser["attendance"].ToList<Attendance>;这一行。它说:

无法将方法组ToList转换为非委托类型。你是想调用这个方法吗?

我该如何访问这些值?

2个回答

39

你打错字了!

attendanceattendence的区别。

这应该可以正常工作。

attender = jUser["attendance"].ToObject<List<Attendance>>();

您可以在DotNetFiddle找到运行结果。


1
但是,“attendance”的拼写是带有“a”,而不是“e”。 :/ - LethalMachine

3

您想要写的内容是:

attender = jUser["attendence"].ToList<Attendance>(); // notice the ()

关于错误: 当您没有放置括号时,C#会认为您想要将函数(委托)ToList分配给变量attender,而不是调用它并分配其返回值。


2
我同意你的答案,但它并没有满足最终问题。我该如何访问这些值? 当使用 ToObject<List<T>>() 时,会抛出 'Newtonsoft.Json.Linq.JToken' does not contain a definition for 'ToList' and the best extension method overload 'System.Linq.Enumerable.ToList<TSource>(System.Collections.Generic.IEnumerable<TSource>)' has some invalid arguments 的错误信息。 - cilerler
CSharpie,谢谢你,很抱歉那是一个愚蠢的错误。但问题是我确实尝试使用(),它抛出了@cilerler提到的错误,但我没有注意到这是不同的错误。最终,我通过将其转换为“List<JToken>”并在for循环中访问每个字符串值来解决了这个问题。再次感谢CSharpie和cilerer。这是我在StackOverflow上的第一篇帖子。 - LethalMachine

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接