c# - DataContractJsonSerializer 没有看到 DataMemberAttribute

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

最佳答案

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

关于c# - DataContractJsonSerializer 没有看到 DataMemberAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2244316/

相关文章:

c# - 如何查找 List<Dictionary<string, object>> 中的重复值?

c# - 从列表中的数组中删除对象

javascript - 使用 JQuery 从 PHP 获取 JSON 响应

php - 在 cordova 中使用 php 和 mysql

c# - 无法使用C#套接字接收字节

c# - 为什么我可以在 App_Code 中访问 ASP.NET 项目的静态类方法而不是 MVC2 项目?

c# - Winforms:插入符位置的屏幕位置

ruby-on-rails - Postgres JSON Rails 查询

c# - 如何在 FSM 中创建状态之间的时间间隔

c# - 在 visual studio 中调用异步 HttpClient.GetAsync() 后调试器停止