For example, I write code like this
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"];
This works fine.
But if I set hasCustomer = false;
JObject c = (JObject)j["customer"];
will throw an System.InValidCastException:
Unable to cast object of type 'Newtonsoft.Json.Linq.JValue' to type 'Newtonsoft.Json.Linq.JObject'.
I was expecting should just assign null to JObject c since JObject is nullable.
So, what's the best way to handle something like this?