如何将 Activator.CreateInstance 与 List一起使用当使用 DataContractJsonSerializer 反序列化 json 时

发布于 2024-10-05 09:00:23 字数 1079 浏览 0 评论 0原文

我正在反序列化这个 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 类的默认构造函数创建的吗?

太感谢了!

I'm deserializing this json string:

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

The class which represents the items is:

[DataContract]
public class MyClass 
{

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

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

        private DateTime _dtcreate;
}

Note that in the default constructor of MyClass I set a default value for "_dtcreate".

So, I'm using this code to Deserialize json into a Array of 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;
    }

When I deserialize a json string I not found in my deserialized array the property "_dtcreate" evalued.

I think DataContractJsonSerializer doesn't use the default constructor of MyClass.

Can I use the

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

to create an instance for all object belonging to the array "gType" to make me ensure that all objects of my list deserialiced are created with the dafault constructor of my T class ?

Thank you so much!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

手长情犹 2024-10-12 09:00:23

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

相反,您应该将逻辑放入 [ OnDeserializing] 方法

DataContract serializers will not run constructors.

Instead, you should put your logic into an [OnDeserializing] method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文