【问题标题】:DataContractJsonSerializer not seeing DataMemberAttributeDataContractJsonSerializer 没有看到 DataMemberAttribute
【发布时间】:2010-02-11 12:21:49
【问题描述】:

我从(优秀的)PropertyBag 类派生,然后想使用 DataContractJsonSerializer 序列化为 Json。不幸的是,动态属性没有显示在 JSON 中,尽管是使用 DataContractAttribute 创建的。如何序列化这些动态属性?

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

【问题讨论】:

    标签: c# .net json serialization


    【解决方案1】:

    “Notes”属性应使用 DataMemberAttribute 进行修饰,以便被 JSON 序列化程序拾取。不是您在此处使用的 DataContractAttirbute。

    【讨论】:

      猜你喜欢
      • 2010-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-10
      • 2017-08-13
      • 2013-10-23
      • 2015-05-12
      • 1970-01-01
      相关资源
      最近更新 更多