例如,我写这样的代码
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"];
这工作正常。
但是如果我设置了 has客户 = 假;
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,因为 JObject 是可空的。
那么,处理这样的事情的最佳方法是什么?
忽略
null,似乎会产生正确的行为。
bool hasCustomer = false ;
JsonSerializer s = new JsonSerializer() {
NullValueHandling = NullValueHandling.Ignore
};
JObject j = JObject.FromObject( new {
customer = hasCustomer ? new {
name = "mike" ,
age = 48
} : null
}, s );
JObject c = (JObject)j[ "customer" ];
JObject 可以为空,但这并不意味着 JObject 可以转换为空。你可以试试这个:
JObject j = JObject.FromObject(new
{
customer = hasCustomer? new
{
name = "mike",
age = 48
}:new Object()
});