Is it possible to create a new JProperty if an object contains a particular variable? For example:
string object = "var2";
var json = new JObject(
new JProperty("var1", var1),
if (object == "var2")
{
new JProperty("var2", var2)
}
);
Any help would be appreciated.
Yes it is. Instead of declaring the extra property in the constructor, you can optionally Add
it afterwards.
string myStr = "var2";
var json = new JObject(
new JProperty("var1", var1));
if (myStr == "var2")
{
json.Add(new JProperty("var2", var2));
}
I usually do this using a Dictionary and then I allow json.net to stitch it together at the end:
var temp = new Dictionary<string,object>();
temp["var1"]=var;
if(mystr=="var2"){
temp["var2"] = var2;
}
//serialize the dictionary using JsonConvert method once you're done
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With