C# Ignore empty Prop in Json

SSinhg 286 Reputation points
2021-08-02T23:29:19.25+00:00

Hi
I want to the empty property in my Json to not show up
Current output
{"fields":{"sum":"Test","pro":{"ke":"T"},"itp":{"id":"10"},"cust":{"id":"13"},"cust7":{}}}

Expected
{"fields":{"sum":"Test","pro":{"ke":"T"},"itp":{"id":"10"},"cust":{"id":"13"}}}

I tried things as suggested here...

My Code

 public static string JiraStructureForCreate(Era eraRequest)
        {
            var tudhjs = new
            {
                fields = new
                {
                    sum = "st",
                    pro = new
                    {
                        ke = "T"
                    },
                    itp = new
                    {
                        id = "35"
                    },
                    cust = new
                    {
                        id = "23"
                    },
                    cust7 = new
                    {
                        value = ""
                    }
                }
            };

            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.NullValueHandling = NullValueHandling.Ignore;
            var myJson = JsonConvert.SerializeObject(tudhjs, settings);
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,648 questions
{count} votes

Accepted answer
  1. Viorel 114.7K Reputation points
    2021-08-03T05:00:51.453+00:00

    Try this approach in your real circumstances:

    var cust7 = new
    {
       value = ""
    };
    
    if( string.IsNullOrWhiteSpace( cust7.value ) ) cust7 = null;
    
    var tudhjs = new
    {
       fields = new
       {
          sum = "st",
          // . . .
          cust = new
          {
             id = "23"
          },
          cust7
       }
    };
    
    1 person found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful