views:

118

answers:

0

I've derived from ( the excellent ) PropertyBag class and then want to serialize to Json using DataContractJsonSerializer. Unfortunately the dynamic properties are not showing up in the JSON despite being created with a DataContractAttribute. How can i serialize these dynamic properties?

using System;
using System.ComponentModel;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

namespace JsonProperties
{
    [DataContract]
    class MyClass : PropertyBag
    {
        static MyClass()
        {
            Attribute att_lat = new DisplayNameAttribute("Latitude");
            Attribute att_data = new DataMemberAttribute();

            Attribute[] attribs_lat = { att_lat, att_data };

            MyClass.AddProperty("_Latitude", typeof(String), attribs_lat);
        }
        [DataMember]
        public Decimal latitude
        {
            get { return (Decimal)this["_Latitude"]; }
            set
            { // Validation etc.
                this["_Latitude"] = value;
            }
        }
    }

    class Program
        {
            static void Main(string[] args)
            {
                Attribute attr1 = new DisplayNameAttribute("Dynamic Note Property");
                Attribute attr2 = new DataContractAttribute();
                Attribute[] attrs = { attr1, attr2 };

                MyClass.AddProperty("Notes", typeof(String), attrs);
                MyClass location = new MyClass();

                location.latitude = 0.1M;
                location["Notes"] = "Some text";

                DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(MyClass));
                dcjs.WriteObject(Console.OpenStandardOutput(), location);
                Console.ReadLine();
            }
        }
    }