C# - How to read 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 Call DataContractJsonSerializer.ReadObject() to deserialize the object from the stream.
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 serializer = new DataContractJsonSerializer(typeof(President));
 
            var path = "president.json";
            using (var fs = new FileStream(path, FileMode.Open))
            {
                var president = (President)serializer.ReadObject(fs);
            }
        }
    }
}
{
  "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