System.Runtime.Serialization.Json.DataContractJsonSerializer

This was added in .NET 3.5


public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Customer person = new Customer();
        person.Name = "Richard Smith";
        person.Entered = new DateTime(2022, 10, 10);

        person.Addresses.Add(new Address());
        person.Addresses.Add( new Address() );
        
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Customer));
        MemoryStream ms = new MemoryStream();
        ser.WriteObject(ms, person);

        string json = Encoding.Default.GetString(ms.ToArray());
        ms.Close();
        Response.Write("<pre>" + Server.HtmlEncode(json) + "</pre>");

        // *** Start from scratch with deserialization
        //ms = new FileStream(Server.MapPath("jsonoutput.txt"), FileMode.Open);
        ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
        
        ser = new DataContractJsonSerializer(typeof(Customer));
        Customer person2 = ser.ReadObject(ms) as Customer;
        ms.Close();

        Response.Write(person2.Name);
    }

    [Serializable]
    public class Customer
    {
        public string Name = "Richard";
        public DateTime Entered = DateTime.Now;
        public List<Address> Addresses = new List<Address>();
    }

    [Serializable]
    public class Address
    {
        public string Street = "20 Oxford Street";
        public string City = "London";
        public string State = "Kensington";
        public string Zip = "SW1 7YH";
    }
}

To serialize you provide the Type to serialize and a Stream to serialize into.
Here a memory stream is used to read the content into a string.
This does quite well with .NET objects and collections/dictionaries.



Deserialization works based on a .NET signature which the incoming JSON data has to match. This means that as long as the inbound JSON object matches the type signature of the type you want to create, the deserialization will work.


DataSets will serialize, but they serialize as an XML string not as an array of rows of objects,


Anonymous types cannot be serialized

Anonymous types cannot be serialized because they are not marked as Serializable
The following will not work.

var TPerson = new { Name = "Rick", Company = "West Wind", Entered = DateTime.Now }; 

DataContractJsonSerializer ser1 = new DataContractJsonSerializer( TPerson.GetType() );
MemoryStream ms1 = new MemoryStream();
ser1.WriteObject(ms1,TPerson);

string json1 = Encoding.Default.GetString(ms1.ToArray());
Response.Write(json1);
ms1.Close();



© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext