使用 C# 反序列化 JSON(多个对象)
本文关键字:对象 反序列化 JSON 使用 | 更新日期: 2023-09-27 18:31:36
我正在尝试反序列化一所学校,然后稍后插入到条形图中。JSON 对象如下所示:
[{"Subject": "TEST APP","AppScores": [{"Season": "AAAAAAAAAAAAAAAAAAAA","year": "1"}, {"Season": "BBBBBBBBBBBBBBBBBBBBB","year": "2"}]}, {"Subject": "TEST APP2","AppScores": [{"Season": "CCCCCCCCCCC","year": "3"}, {"Season": "DDDDDDDDDDDDDDDDD","year": "4"}]}]
我希望在Console.WriteLine();
中看到的输出
Subject: TEST APP
AppScores
Season: AAAAAAAAAAAAAAAAAAAA
Year: 1
Season: BBBBBBBBBBBBBBBBBBBBB
Year: 2
Subject: TESTAPP2
AppScores
Season: CCCCCCCCCCC
Year: 3
Season: DDDDDDDDDDDDDDDDD
Year: 4
我已经看到使用下面的类似代码以多种方式完成此操作。
School subject = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<School>(json);
foreach (var item in subject.data)
{Console.WriteLine("season: {0}, year: {1}", item.season, item.year); Console.ReadLine();}
从类调用:
public class School
{
public List<SchoolSubjects> data { get; set; }
}
public class SchoolSubjects
{
public string year { get; set; }
public string season { get; set; }
}
任何人都可以帮助修改此代码,因为我找不到任何可以执行此操作的示例?提前谢谢。
您的问题是根 JSON 容器是一个数组,而不是一个对象:
-
数组是值的有序集合。数组以
[
(左括号)开头,以]
(右括号)结尾。值用,
(逗号)分隔。 -
对象是一组无序的名称/值对。对象以
{
(左大括号)开头,以}
(右大括号)结尾。
JSON 数组需要反序列化为集合,例如 List<T>
。
如果我将您的 JSON 上传到 http://json2csharp.com/,我会得到以下类,重命名更合适:
public class SchoolSubjectAppScore
{
public string Season { get; set; }
public string year { get; set; }
}
public class SchoolSubject
{
public SchoolSubject() { this.AppScores = new List<SchoolSubjectAppScore>(); }
public string Subject { get; set; }
public List<SchoolSubjectAppScore> AppScores { get; set; }
}
然后,可以按如下方式反序列化和打印 JSON:
var root = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<List<SchoolSubject>>(json);
foreach (var subject in root)
{
Console.WriteLine(subject.Subject);
foreach (var item in subject.AppScores)
{
Console.WriteLine("season: {0}, year: {1}", item.Season, item.year);
}
}