隨着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