たとえば、私はこのようなコードを書きます
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'.
JObjectはnull可能であるため、JObject cにnullを割り当てるだけでよいと思っていました。
では、このようなものを処理する最善の方法は何ですか?