Json.net linq to json将null转换为JObject抛出异常

时间:2012-08-16 16:54:40

标签: c# null json.net

例如,我写这样的代码

        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可以为空,我原本应该为JObject c赋予null。

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

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

JObject可以为空,但这并不意味着JObject可以抛出null。 你可以试试这个:

JObject j = JObject.FromObject(new
        {
            customer = hasCustomer? new
            {
                name = "mike",
                age = 48
            }:new Object()
        });