【问题标题】:How to use Activator.CreateInstance with List<T> when Deserialize json with DataContractJsonSerializer使用 DataContractJsonSerializer 反序列化 json 时如何将 Activator.CreateInstance 与 List<T> 一起使用
【发布时间】:2010-11-28 18:45:42
【问题描述】:

我正在反序列化这个 json 字符串:

[{"id":"1"},{"id":"2"},{"id":"3"}]

代表项目的类是:

[DataContract]
public class MyClass 
{

        public MyClass() {
            this._dtcreate = new DateTime();
        }

        private int _id;
        [DataMember(Name = "id")]
        public int Id {get;set;}

        private DateTime _dtcreate;
}

请注意,在 MyClass 的默认构造函数中,我为“_dtcreate”设置了默认值。

所以,我正在使用此代码将 json 反序列化为 T 数组:

 public static T[] DeserializeArray<T>(string json)
    {
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T[]));
        MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
        T[] gType = (T[])ser.ReadObject(ms);
        return gType;
    }

当我反序列化一个 json 字符串时,我在反序列化的数组中找不到属性“_dtcreate”。

我认为 DataContractJsonSerializer 没有使用 MyClass 的默认构造函数。

我可以用吗

T obj = Activator.CreateInstance<T>();

为属于数组“gType”的所有对象创建一个实例,以确保我的反序列化列表中的所有对象都是使用我的 T 类的默认构造函数创建的?

非常感谢!

【问题讨论】:

  • DateTime 是一个结构。你的构造函数完全没用。

标签: json list windows-phone-7 activator deserialization


【解决方案1】:

DataContract 序列化程序不会运行构造函数。

相反,您应该将您的逻辑放入an [OnDeserializing] method

【讨论】:

  • 谢谢!我设置 this._dtcreate = new DateTime();在 OnDeserializedMethod 和工作正常..
  • @Nicola:你根本不需要这样做。由于 DateTime 是一个值类型,它会自动设置为其默认值。不能是null。您可能正在寻找DateTime.Now
  • 属性“_dtcreate”只是一个例子。我真的有一个字符串属性可以设置默认值。感谢您的支持!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多