0

I have this method:

private string serializeResult(string errorCode = null, string parameter1 = null, string parameter2 = null, string context = null)
{
    return JsonConvert.SerializeObject(new
    {
        errorCode,
        parameter1,
        parameter2,
        context 
    });
}

Now if context, errorCode, parameter1 or parameter2 is null, I don't want them to be added for the anonymous type.

How can I do that without testing all kind of options (I have much more parameters, this is a smaller problem)?

Kenny Smith
  • 729
  • 3
  • 9
  • 23
  • 2
    The real question is why don't you just tell JSON.NET not to serialize nulls? – ProgrammingLlama Dec 07 '20 at 09:15
  • Does this answer your question? [Is it possible to modify or remove an anonymous type from an object in c#?](https://stackoverflow.com/questions/14365858/is-it-possible-to-modify-or-remove-an-anonymous-type-from-an-object-in-c) – SomeBody Dec 07 '20 at 09:20

2 Answers2

6

Rather than messing with the anonymous class, provide a custom JSON serialisation setting:

return JsonConvert.SerializeObject(new
    {
        errorCode,
        parameter1,
        parameter2,
        context 
    }, new JsonSerializerSettings
    {
        NullValueHandling = NullValueHandling.Ignore
    });

Note that it doesn't make sense to conditionally remove a value from an anonymous class in general. Suppose you could do this somehow, what would happen if you tried to access:

var anonClass = new
    {
        errorCode ?? removeIfNull, // fake syntax
        parameter1,
        parameter2,
        context 
    };
anonClass.errorCode // will this access succeed? We don't know until runtime!
Sweeper
  • 213,210
  • 22
  • 193
  • 313
1

You can ignore null values from serializer as below. Please also refer How to ignore a property in class if null, using json.net

return JsonConvert.SerializeObject(new
{
    errorCode,
    parameter1,
    parameter2,
    context 
}, Newtonsoft.Json.Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
Karan
  • 12,059
  • 3
  • 24
  • 40