本文介紹了如何將 JSON 反序列化為 IEnumerable<BaseType>使用 Newtonsoft JSON.NET的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
鑒于此 JSON:
[
{
"$id": "1",
"$type": "MyAssembly.ClassA, MyAssembly",
"Email": "me@here.com",
},
{
"$id": "2",
"$type": "MyAssembly.ClassB, MyAssembly",
"Email": "me@here.com",
}
]
還有這些類:
public abstract class BaseClass
{
public string Email;
}
public class ClassA : BaseClass
{
}
public class ClassB : BaseClass
{
}
如何將 JSON 反序列化為:
How can I deserialize the JSON into:
IEnumerable<BaseClass> deserialized;
我不能使用 JsonConvert.Deserialize<IEnumerable<BaseClass>>()
因為它抱怨 BaseClass
是抽象的.
I can't use JsonConvert.Deserialize<IEnumerable<BaseClass>>()
because it complains that BaseClass
is abstract.
推薦答案
你需要:
JsonSerializerSettings settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
};
string strJson = JsonConvert.SerializeObject(instance, settings);
所以 JSON 看起來像這樣:
So the JSON looks like this:
{
"$type": "System.Collections.Generic.List`1[[MyAssembly.BaseClass, MyAssembly]], mscorlib",
"$values": [
{
"$id": "1",
"$type": "MyAssembly.ClassA, MyAssembly",
"Email": "me@here.com",
},
{
"$id": "2",
"$type": "MyAssembly.ClassB, MyAssembly",
"Email": "me@here.com",
}
]
}
然后就可以反序列化了:
Then you can deserialize it:
BaseClass obj = JsonConvert.DeserializeObject<BaseClass>(strJson, settings);
文檔:TypeNameHandling 設置
這篇關于如何將 JSON 反序列化為 IEnumerable<BaseType>使用 Newtonsoft JSON.NET的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!