Json.NET:基础对象中的序列化回调

时间:2011-06-14 22:11:30

标签: c# .net json serialization json.net

使用Json.NET是OnDeserializedAttribute放在基类方法上时支持的序列化回调吗?例如,使用此对象图:

[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

1 个答案:

答案 0 :(得分:1)

是。支持OnDeserialized。见the documentation

这是一个有效的cs-script示例。需要Newtonsoft.Json.dll是同一个目录

//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
    }
}

打印

1