之前接 API 時,有用 Json.NET 的 JObject 直接抓目標資料,這次心血來潮老老實實的把該對應 class 建出來,反序列化一直出問題,最後還是透過
[VS] 選擇性貼上 功能把對應 class 自動建立出來,才發現腦殘的點在哪,Orz
在 LinqPad 上筆記該範例作為借鏡
void Main()
{
MasterClass demoData = new MasterClass()
{
MasterProp = "MasterProp",
InnerClass = new InnerClass() { InnerProp1 = "InnerProp1", InnerProp2 = "InnerProp2", InnerProp3 = "InnerProp3" },
DetailMasterClass = new DetailMasterClass()
{
DetailMasterProp = "dmProp",
DetailClass = new List<DetailClass>()
{
new DetailClass(){DetailProp1 = "dProp1" , DetailProp2 = "dProp2"},
new DetailClass(){DetailProp1 = "dProp11" , DetailProp2 = "dProp22"},
}
}
};
// 序列化
string jsonData = JsonConvert.SerializeObject(demoData);
jsonData.Dump("序列化");
// 反序列化-方法一
JObject jsonObject = JObject.Parse(jsonData);
string records = jsonObject[nameof(MasterClass.DetailMasterClass)][nameof(DetailClass)].ToString();
List<DetailClass> result = JsonConvert.DeserializeObject<List<DetailClass>>(records);
result.Dump("使用 JObject 取 DetailClass 資料");
// 反序列化-方法二
var descJson = JsonConvert.DeserializeObject<MasterClass>(jsonData);
descJson.Dump("完整 json 資料");
descJson.DetailMasterClass.DetailClass.Dump("只取 DetailClass 資料");
}
public class MasterClass
{
public string MasterProp { get; set; }
public InnerClass InnerClass { get; set; }
public DetailMasterClass DetailMasterClass { get; set; }
}
public class InnerClass
{
public string InnerProp1 { get; set; }
public string InnerProp2 { get; set; }
public string InnerProp3 { get; set; }
}
public class DetailMasterClass
{
public string DetailMasterProp { get; set; }
public List<DetailClass> DetailClass { get; set; }
}
public class DetailClass
{
public string DetailProp1 { get; set; }
public string DetailProp2 { get; set; }
}
在
Json Init 內格式化 json 資料,方便閱讀
LinqPad 輸出的完整資料