Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditionally adding a new json.net JProperty

Tags:

json

c#

json.net

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.

like image 846
Rex_C Avatar asked Sep 15 '25 01:09

Rex_C


2 Answers

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));
}
like image 117
Tim S. Avatar answered Sep 17 '25 16:09

Tim S.


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
like image 22
Xavier J Avatar answered Sep 17 '25 15:09

Xavier J