2016-12-16 106 views
1

我想根据条件语句的结果在JObject中添加JProperty字段,但我在格式化代码时遇到问题。如何在Json.Net对象中基于条件语句添加JProperty

string zip = "00000"; 
bool isNull = string.IsNullOrEmpty(str); 

JObject jsonContent = new JObject(
      new JProperty("email_address", subscriber.Email), 
      new JProperty("status", "subscribed"), 
      if(!isNull) 
      { 
       new JProperty("ZIP", str), 
      } 
      new JProperty("state": "NY") 
     ); 

问题是如何处理上一行的逗号以及如何格式化JSON对象中的条件语句。

回答

1

您可以稍后根据您的情况添加属性,以下情况如何?

string zip = "00000"; 
bool isNull = string.IsNullOrEmpty(str); 

JObject jsonContent = new JObject(
      new JProperty("email_address", subscriber.Email), 
      new JProperty("status", "subscribed"), 
      new JProperty("state": "NY") 
     ); 
if(isNull) { 
    jsonContent["ZIP"] = str; 
} 
相关问题