Json.NET:序列化回调的基础对象 [英] Json.NET: Serialization Callbacks in base object

查看:141
本文介绍了Json.NET:序列化回调的基础对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用Json.NET被序列化回调支持当OnDeserializedAttribute被放置在基类方法?例如使用该对象图:

  [DataContract]
公共类StubData:StubBase {}

[DataContract]
公共类StubBase {
    公共字符串ID {获得;组; }

    [OnDeserialized]
    公共无效OnDeserialized(的StreamingContext上下文){
        的id =1;
    }
}

VAR stubData = JsonConvert.DeserializeObject< StubData>(@{AnyDATA公司:富});

stubData.Id //返回1
 

解决方案

是的。 OnDeserialized 支持。请参阅<一href="http://james.newtonking.com/projects/json/help/index.html?topic=html/SerializationCallbacks.htm"相对=nofollow称号=Json.Net文件>

下面是一个工作 CS-脚本的例子。需要Newtonsoft.Json.dll是相同的目录

  // css_ref Newtonsoft.Json.dll

使用系统;
使用System.Windows.Forms的;
使用Newtonsoft.Json;
使用System.Runtime.Serialization;

公共类StubData:StubBase {}

公共类StubBase {
    公共字符串ID {获得;组; }

    [OnDeserialized]
    公共无效OnDeserialized(的StreamingContext上下文){
        的id =1;
    }
}

类脚本
{
    [STAThread]
    静态公共无效的主要(字串[] args)
    {
      VAR stubData = JsonConvert.DeserializeObject&LT; StubData&GT;(@{AnyDATA公司:富});
      Console.WriteLine(stubData.Id); //返回1
    }
}
 

这版画

  1
 

Using Json.NET are Serialization Callbacks supported when the OnDeserializedAttribute is placed on a base class method? For example using this object graph:

[DataContract]
public class StubData:StubBase {}

[DataContract]
public class StubBase {
    public string Id { get; set; }

    [OnDeserialized]
    public void OnDeserialized(StreamingContext context) {
        Id = "1";
    }
}

var stubData = JsonConvert.DeserializeObject<StubData>(@"{""anyData"":""Foo""}");

stubData.Id //returns 1

解决方案

Yes. OnDeserialized is supported. See the documentation

Here's a working cs-script example. Needs Newtonsoft.Json.dll is the same directory

//css_ref Newtonsoft.Json.dll

using System;
using System.Windows.Forms;
using Newtonsoft.Json;
using System.Runtime.Serialization;

public class StubData:StubBase {}

public class StubBase {
    public string Id { get; set; }

    [OnDeserialized]
    public void OnDeserialized(StreamingContext context) {
        Id = "1";
    }
}

class Script
{
    [STAThread]
    static public void Main(string[] args)
    {
      var stubData = JsonConvert.DeserializeObject<StubData>(@"{""anyData"":""Foo""}");
      Console.WriteLine(stubData.Id); //returns 1
    }
}

This prints

1

这篇关于Json.NET:序列化回调的基础对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆