Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Json.net linq to Json将null强制转换为JObject抛出异常_C#_Null_Json.net - Fatal编程技术网

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" ];