2012-08-16 69 views
1

例如,我寫這樣的代碼Json.net的LINQ to JSON投零到JObject拋出異常

 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,因爲C JObject可爲空。

那麼,處理這樣的事情的最佳方法是什麼?

回答

2

忽略空,似乎產生正確的行爲。

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

JObject可以爲空,但這並不意味着JObject可以投射null。 你可以試試這個:

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