我想根据条件语句的结果在JObject
中添加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对象中的条件语句。
您可以根据条件以后添加该属性,以下呢?
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;
}
您可以根据条件实例化JProperty
或null
,然后在属性周围设置查询以跳过null
,如:
var obj =
new JObject(
from p in new[]
{
new JProperty("email_address", subscriber.Email),
new JProperty("status", "subscribed"),
// conditional property:
zip is not null ? new JProperty("ZIP", zip) : null,
new JProperty("state", "NY")
}
where p is not null // skip null properties
select p);
当您将复杂的JSON对象设置为单个表达式时,这可能会有所帮助。如果查询部分打扰,则可以将其塞在辅助方法后面:
using static JsonNetHelpers; // import members of this type
var obj =
JObject( // invokes "JObject" method; not "JObject" constructor (new missing)
new JProperty("email_address", subscriber.Email),
new JProperty("status", "subscribed"),
// conditional property:
zip is not null ? new JProperty("ZIP", zip) : null,
new JProperty("state", "NY"));
static class JsonNetHelpers
{
public static JObject JObject(params JProperty?[] properties) =>
new JObject(from p in properties where p is not null select p);
}