我正在嘗試反序列化一個物件,該物件基本上有一個物件陣列,每個物件都有一個帶有物件型別和物件實體的屬性。該模式看起來有點像這樣:
public class MainObject
{
public IEnumerable< Parent> Parents { get; set; }
}
public class Parent
{
public string NameOfChildObjectType { get; set; }
public Object Child { get; set; }
}
public class Child_1
{
//some props {
}
public class Child_2
{
//some props but different as child 1 or 3 {
}
public class Child_3 ?
{
//完全不同的道具,實際上我們唯一的共同點是我們是孩子。
}
和Json檔案
{
"id"。"1"。
"Name": "MainObjectName",
"Parents": [
{
"ChildName": "ChildOfType1",
"引數": {
"Name": "Jordan"。
}
},
{
"ChildName": "ChildOfType2",
"引數": {
"高度": "6`2"。
}
},
{
"ChildName": "ChildOfType3",
"引數": {
"OwnedPets": [
{
"DogName": "JJ",
"FishName": "Shrimp", "FishName".
}
],
"MaxHeadRotation": "45"
那么,我是否有辦法定義一個不被串列中所有物件共享的通用型別,或者甚至一次性地反序列化它們? 任何想法都是值得贊賞的。
uj5u.com熱心網友回復:
我在Visual Studio中進行了測驗,一切作業正常
var json= ... your json string
var jD = JsonConvert.DeserializeObject<Root>(json)。
類
public class Root
{
public string id { get; set; }
public string Name { get; set; }
public List<Parent> Parents { get; set; }
}
public class OwnedPetpublic string DogName { get; set; }
public string FishName { get; set; }
}
public class Parameters
{
public string Name { get; set; }
public string Height { get; set; }
public List<OwnedPet> OwnedPets { get; set; }
public string MaxHeadRotation { get; set; }
}
public class Parent
{
public string ChildName { get; set; }
public Parameters引數 { get; set; }
你可以嘗試用Dictionary<string, object>代替Parameters類,但無論如何,在這之后你將需要類來將物件轉換為型別。我無法想象,如果你不知道物件的內部是什么,你將如何使用資料
。轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/311759.html
標籤:
