随着Newtonsoft.Json可以deserialise到通过非通用超载的类型DeserializeObject(string value, type type)
。
这意味着您可以使用Type
属性作为要反序列化的类型的提示。
- deserialise基地型
实际
Action
对象
- 获取类型类型全名的
- 获取类型名称
- deserialise派生动作类型
请看下面的例子:
using System;
using Newtonsoft.Json;
namespace com.example.SO42736347
{
public class Action
{
public string Type { get; set; }
}
public class Action1 : Action
{
public string Data { get; set; }
}
public class Program
{
public const string ACTION1 = @"{
""Type"" : ""com.example.Json.Action1"",
""Data"" : ""41°24'12.2 N 2°10'26.5""
}";
public static void Main()
{
var action = JsonConvert.DeserializeObject<Action>(ACTION1);
var type = Type.GetType(action.Type);
var action1 = (Action1) JsonConvert.DeserializeObject(ACTION1, type);
}
}
}
如果您不想在Type
字段中指定完整限定类型名称,则可以使用自定义程序逻辑(例如,以基名称空间为前缀)。
编辑:根据意见,应该能够deserialise的动作列表(派生类)。因此,我追加下面的例子来我的答案,你可以看到,如何通过执行以下操作来deserialise的操作的列表:在Action
的
- deserialise仿制JArray
- 在阵列中的每个项目确定
Type
- deserialise到特定派生类型
我还添加了循环转换后以显示如何进一步处理转换后的动作。
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
namespace com.example.Json
{
public class Action
{
public string Type { get; set; }
}
public class Action1 : Action
{
public string Data { get; set; }
}
public class Action2 : Action
{
public string SomeProperty { get; set; }
}
public class Program
{
public const string ACTION1 = @"{
""Type"" : ""com.example.Json.Action1"",
""Data"" : ""41°24'12.2 N 2°10'26.5""
}";
public const string ACTION2 = @"{
""Type"" : ""com.example.Json.Action2"",
""SomeProperty"" : ""arbitrary-value""
}";
public const string ACTIONS =
"[" +
ACTION1 +
"," +
ACTION2 +
"]" ;
public static void Main()
{
var actions = new List<Action>();
JArray jArray = JArray.Parse(ACTIONS);
foreach(var item in jArray)
{
var json = JsonConvert.SerializeObject(item);
var baseAction = JsonConvert.DeserializeObject<Action>(json);
var type = Type.GetType(baseAction.Type);
var action = (Action) JsonConvert.DeserializeObject(json, type);
actions.Add(action);
}
// now that we have converted all array items into specific derived action objects
// we can start processing them anyway we want
// keep in mind that you have to check the runtime type in order to find out what
// specific kind of action we have
// eg.
foreach(var action in actions)
{
switch(action.Type)
{
case "com.example.Json.Action1":
// do something
Console.WriteLine("found com.example.Json.Action1");
Console.WriteLine((action as Action1).Data);
break;
case "com.example.Json.Action2":
// do something
Console.WriteLine("found com.example.Json.Action2");
Console.WriteLine((action as Action2).SomeProperty);
break;
default:
// do something
Console.WriteLine("found something else");
break;
}
}
}
}
}
这不是有效的JSON ... –
是'action'数组还是对象? –
@GeneR这是一个对象,现在它有效,对不起! – Greggz