C# Json.net linq to Json将null强制转换为JObject抛出异常
例如,我编写这样的代码C# Json.net linq to Json将null强制转换为JObject抛出异常,c#,null,json.net,C#,Null,Json.net,例如,我编写这样的代码 bool hasCustomer = true; JObject j = JObject.FromObject(new { customer = hasCustomer? new { name = "mike", age = 48 }:null });
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,因为JObject是可以为null的
那么,处理这种情况的最佳方法是什么?JObject可以为null,但这并不意味着JObject可以强制转换null。 您可以尝试以下方法:
JObject j = JObject.FromObject(new
{
customer = hasCustomer? new
{
name = "mike",
age = 48
}:new Object()
});
忽略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" ];