'How to add a JProperty based on conditional statement within a Json.Net object
I want to add a JProperty
field in a JObject
based on the result of a conditional statement, but I'm having trouble formatting the code.
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")
);
Problem is how to handle the comma on the previous row and just how in particular to format the conditional statement within the JSON object.
Solution 1:[1]
You can add the property later based on your condition, what about the following?
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;
}
Solution 2:[2]
You could instantiate a JProperty
or null
based on a condition, and then setup a query around the properties to skip those that are null
, as in:
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);
This can be helpful when you are setting up a complex JSON object as a single expression. If the query part bothers, then it can be tucked behind a helper method:
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);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | james_bond |
Solution 2 | Atif Aziz |