1
例如,我寫這樣的代碼Json.net的LINQ to JSON投零到JObject拋出異常
bool hasCustomer = true;
JObject j = JObject.FromObject(new
{
customer = hasCustomer? new
{
name = "mike",
age = 48
}:null
});
JObject c = (JObject)j["customer"];
if (c != null)
string name = (string) c["name"];
這工作得很好。
但是,如果我設置hasCustomer = false;
JObject c = (JObject)j["customer"];
將拋出System.InValidCastException:
Unable to cast object of type 'Newtonsoft.Json.Linq.JValue' to type 'Newtonsoft.Json.Linq.JObject'.
我期待應該只分配null以JObject C,因爲C JObject可爲空。
那麼,處理這樣的事情的最佳方法是什麼?