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)?

2

2 Answers 2

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!
Sign up to request clarification or add additional context in comments.

Comments

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});

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.