I am trying to deserialize JSON into List. I have .NET 4.0. Normal deserialization into an object works fine. I am an absolute beginner in C#.
I wrote the following code with the help from various forums. When I am trying to load the deserialized JSON into a List for Lad type, it doesn't give any error but when I check Lads object it's just blank.
using System;
using System.Net;
using System.Runtime.Serialization.Json;
using System.Web.Script.Serialization;
using System.Collections.Generic;
namespace RESTServicesJSONParserExample
{
public class MyDate
{
public int year { get; set; }
public int month { get; set; }
public int day { get; set; }
}
public class Lad
{
public string firstName { get; set; }
public string lastName { get; set; }
public MyDate dateOfBirth { get; set; }
}
class Program
{
static void Main()
{
var obj = new Lad
{
firstName = "Markoff",
lastName = "Chaney",
dateOfBirth = new MyDate
{
year = 1901,
month = 4,
day = 30
}
};
var json = new JavaScriptSerializer().Serialize(obj);
Console.WriteLine(json);
//This fails to load desereialized JSON in the List
List<Lad> Lads = new JavaScriptSerializer().Deserialize<List<Lad>>(json);
Lad Lad1 = new JavaScriptSerializer().Deserialize<Lad>(json);
Console.WriteLine(Lad1.firstName);
//Nothing returned here
foreach (Lad Lad2 in Lads)
{
Console.WriteLine(Lad2.firstName);
}
Console.ReadLine();
}
}
}