1

I am trying to dynamically create a JSON object based on the values provided to me.

1st Scenario - I have all the values

 string param1 = "Hey";
 string param2 = "Bye";
 string param3 = "Later";

I would derive my Json like so:

 private string BuildJson (string param1, string param2, string param3)
 {
       //Passed values for example
      //param1 = "Hey";
      //param2 = "Bye";
      //param3 = "Later";

      object jJson = new 
      {
          VALS= new 
             {
                 val1 = param1,
                 val2 = param2,
                 val3 = param3
             }
      };

      return JsonConvert.SerializeObject(jJson );
 }

And this works great. However, now I'm trying to find a way to create this same JSON object, without knowing which param will have values. If there is no value, then I don't want my jJson to have that property.

So for example

  private string BuildJson (string param1, string param2, string param3)
  {
   //Passed values for example
  //param1 = "Hey";
  //param2 = null;
  //param3 = "Later";

  //Since param2 is NULL, I would NOT want to have it all together in my JSON like below

  object jJson = new 
  {
      VALS= new 
         {
             val1 = param1,
             val3 = param3
         }
  };

  return JsonConvert.SerializeObject(jJson );
}

Is there an alternative way to dynamically create JSON like this? Thanks.

1

1 Answer 1

3

Since this is Newtonsoft, just include NullValueHandling = NullValueHandling.Ignore

Given

private static string BuildJson(string param1, string param2, string param3)
{

   object jJson = new
   {
      VALS = new
      {
         val1 = param1,
         val2 = param2,
         val3 = param3
      }
   };

   return JsonConvert.SerializeObject(jJson, 
      Formatting.Indented,
      new JsonSerializerSettings()
      {
         NullValueHandling = NullValueHandling.Ignore
      });
}

Usage

var result = BuildJson("asd", null, "sdf");
Console.WriteLine(result);

Output

{
  "VALS": {
    "val1": "asd",
    "val3": "sdf"
  }
}

Disclaimer : I would recommend Text.Json for any greenfield development, and would also dissuade you from using anonymous types like this and instead use actual concrete models.

Sign up to request clarification or add additional context in comments.

1 Comment

Disclaimer noted. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.