DataContractJsonSerializer没有看到DataMemberAttribute

时间:2010-02-11 12:21:50

标签: c# .net json serialization

我从(优秀的)PropertyBag类派生,然后想要使用DataContractJsonSerializer序列化为Json。遗憾的是,尽管使用DataContractAttribute创建了动态属性,但JSON中并未显示动态属性。如何序列化这些动态属性?

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();
            }
        }
    }

1 个答案:

答案 0 :(得分:1)

“Notes”属性应该使用DataMemberAttribute进行修饰,以便JSON序列化程序获取它。不是DataContractAttirbute,正如您在这里使用的那样。