我一直在搜索论坛和JSON.NET网站在这个问题上,从我可以看到我正确地遵循指导原则,但它无法正常工作。JSON.NET反序列化派生类不能正常工作
我想从派生类反序列化对象。 序列化工作正常,但是当反序列化它试图反序列化到错误的类型。
我想随着Windows Phone 8和JSON.NET做到这一点4.5.11
我有以下类这我序列化:
public class MyClass : ModelBase
{
public string Title { get; set; }
[JsonProperty(TypeNameHandling = TypeNameHandling.All)]
public MyAction Action {get; set; }
}
public abstract class MyAction : ModelBase
{
[JsonIgnore()]
public abstract ActionType ActionType { get; }
public abstract void Execute();
}
public class SettingsAction : MyAction
{
public override ActionType ActionType
{
get { return ActionType.Settings; }
}
public SettingsType SettingsType {get; set; }
public override void Execute()
{
}
}
public class NoneAction : MyAction
{
public override ActionType ActionType
{
get { return ActionType.None; }
}
public override void Execute()
{
return;
}
}
序列化这样的:
MyClass obj = new MyClass
{
Action = new SettingsAction()
};
string json = JsonConvert.SerializeObject(
obj,
Formatting.Indented,
new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All });
using (StreamWriter writer = new StreamWriter(stream))
{
writer.Write(json);
}
,它给我下面的JSON:
{
"$type": "Model.MyClass, Model",
"Title": null,
"Action": {
"$type": "Model.SettingsAction, Model",
"SettingsType": 0
}
}
据我所知,这是正确的,我告诉它包括类型信息,它正确包括在内。
的我反序列化这样的:
using (StreamReader r = new StreamReader(stream))
{
string json = r.ReadToEnd();
MyClass obj = JsonConvert.DeserializeObject<MyClass>(json);
}
而且我得到以下错误:
JsonSerializationException:错误设置值 'SettingsType' 上 'Model.NoneAction'
所以,虽然类型包含在JSON中,但在序列化时却忽略了它,当然,将它反序列化为不同的类型也会失败。
有没有人有一个想法,为什么它没有考虑到信息和反序列化到正确的类型?
你有没有试过在DeserializeObject调用中使用相同的'JsonSerializerSettings'? – 2013-04-07 18:11:50
是的,在发布问题后我尝试了这个,但无济于事,依然是同样的错误。 – Kenneth 2013-04-07 18:13:48
'DeserializeObject'中的''是什么? –
2013-04-07 18:26:53