【问题标题】:How to retain base class field values after Deserialization?反序列化后如何保留基类字段值?
【发布时间】:2017-04-24 23:03:11
【问题描述】:

我有一个类“Employee”,它继承自抽象基类“Person”。我在客户端序列化 Employee 类并将其发送到处理 Employee 记录并向我返回 Employee 对象的 wcf 服务。

但是我们有这个奇怪的要求,因为服务端的 Employee 类不是从“Person”继承的,而 Employee 只是一个单一的实体。为此,我在客户端将 Person 的所有字段都标记为“NonSerialized()”(我不想向 wcf 服务发送不必要的字段)。

在客户端,我想将 Employee json 对象反序列化为现有的 Employee 类(从 Person 继承),但要注意的是,我想在不丢失 Employee 对象中抽象基类“Person”的现有字段值的情况下做到这一点。

在反序列化员工 json 对象后,我成功获取了 Employee 对象的所有值,但“Person”类的所有现有字段都变为空。我正在使用 Microsoft 的“DataContractJsonSerializer”进行反序列化。任何帮助表示赞赏。

下面是客户端的代码:

//Creating employee initializes fields of Person class to some values    
var employee = new Employee();

//Code here to call WCF and get response back
DeserializeResponse(out employee, jsonResponse);


private TContract DeserializeResponse<TContract>(out TContract dataContract, string jsonResponse)
            where TContract : class, new()
        {     
            var jsonSerializer = new DataContractJsonSerializer(typeof(TContract));
            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(response)))
            {
//employee loses all the Person values after deserialization here
                dataContract = jsonSerializer.ReadObject(ms) as TContract;
            }       
            return dataContract;
        }

【问题讨论】:

    标签: c# .net wcf deserialization


    【解决方案1】:

    您的 Employee 类是 .NET 中的 reference type。设置dataContract = jsonSerializer.ReadObject(ms) as TContract; 将改变dataContract 持有的引用,指向一个新的内存位置。那时你的旧对象已经消失了。

    更好的选择可能是在 Person 基类上使用 SetPersonDefaults 方法,您可以在反序列化数据后在构造函数和 employee 对象上调用该方法。

    //Creating employee initializes fields of Person class to some values    
    var employee = new Employee();
    
    //Code here to call WCF and get response back
    DeserializeResponse(out employee, jsonResponse);
    
    employee.SetPersonDefaults();
    

    【讨论】:

    • 感谢您的回复。我最终使用 Newtonsoft Json.net 库进行反序列化,因为它保留了与 DataContractJsonSerializer 不同的基类字段值。
    猜你喜欢
    • 2018-12-11
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    • 1970-01-01
    • 2016-07-16
    • 2021-11-28
    • 2017-08-17
    • 2022-01-09
    相关资源
    最近更新 更多