C# - How to write JSON using DataContractJsonSerializer

1 Mark up the class to be serialized with DataContract and DataMember attributes.
2 Pass the type to be serialized to the DataContractJsonSerializer constructor.
3 Create a JSON writer using JsonReaderWriterFactory.CreateJsonWriter().
4 Call DataContractJsonSerializer.WriteObject(writer, object) to serialize object to writer.
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
 
namespace Zuga.net
{
    [DataContract]
    public class President
    {
        [DataMember] public int Number { get; set; }
        [DataMember] public string First { get; set; }
        [DataMember] public string Last { get; set; }
        [DataMember] public int Year { get; set; }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            var president = new President()
            {
                Number = 1,
                First = "George",
                Last = "Washington",
                Year = 1789
            };
 
            var serializer = new DataContractJsonSerializer(typeof(President));
 
            var path = "president.json";
            using (var fs = new FileStream(path, FileMode.Create))
            {
                var encoding = Encoding.UTF8;
                var ownsStream = false;
                var indent = true;
 
                using (var writer = JsonReaderWriterFactory.CreateJsonWriter(fs, encoding, ownsStream, indent))
                {
                    serializer.WriteObject(writer, president);
                }
            }
        }
    }
}
{
  "First": "George",
  "Last": "Washington",
  "Number": 1,
  "Year": 1789
}

Ads by Google


Ask a question, send a comment, or report a problem - click here to contact me.

© Richard McGrath