Search code examples
c#serializationdeserializationjson-deserializationjavascriptserializer

Deserialize JSON with C# (Multiple Objects)


I'm trying to deserialize a School to then insert into a Bar Chart Later. The JSON object looks like:

[{"Subject": "TEST APP","AppScores": [{"Season": "AAAAAAAAAAAAAAAAAAAA","year": "1"}, {"Season": "BBBBBBBBBBBBBBBBBBBBB","year": "2"}]}, {"Subject": "TEST APP2","AppScores": [{"Season": "CCCCCCCCCCC","year": "3"}, {"Season": "DDDDDDDDDDDDDDDDD","year": "4"}]}]

The output I am hoping to see in the 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

I have seen this been done in multiple of ways using similar code below.

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();}

Calling from a Class:

public class School
{
public List<SchoolSubjects> data { get; set; }
}
public class SchoolSubjects
{
public string year { get; set; }
public string season { get; set; }
}

Can anyone help to amend this code as I cant find any examples that would do this? Thanks in advance.


Solution

  • Your problem is that your root JSON container is an array, not an object:

    • An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

    • An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace).

    A JSON array needs to be deserialized into a collection, such as a List<T>.

    If I upload your JSON to http://json2csharp.com/, I get the following classes, renamed more appropriately:

    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; }
    }
    

    Then your JSON can be deserialized and printed as follows:

            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);
                }
            }