1

例如,我写这样的代码

        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 可以为空。

那么,处理这样的事情的最佳方法是什么?

4

2 回答 2

4

忽略 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" ];
于 2012-08-16T17:21:18.503 回答
-1

JObject 可以为空,但这并不意味着 JObject 可以强制转换为空。你可以试试这个:

JObject j = JObject.FromObject(new
        {
            customer = hasCustomer? new
            {
                name = "mike",
                age = 48
            }:new Object()
        });
于 2012-08-16T17:12:15.483 回答