使用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
答案 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