Skip to content

Globally ignore null values for all properties and subclasses (without JsonSerializerOptions) #30359

@Joelius300

Description

@Joelius300

Because IJSRuntime won't support customizable serialization there is currently no way of using JsonSerializerOptions with IgnoreNullValues = true. This seems like a functionality which shouldn't be missing as it leads to dead-ends really fast - but sadly the AspNetCore-team has confirmed that this is not planned and won't be added.

To work around this I thought of something like a JsonIgnoreNullValuesAttribute.

You could use the JsonIgnoreNullValuesAttribute on the whole class or single properties. Furthermore it would be nice to have something like a Recursive: bool-property on the JsonIgnoreNullValuesAttribute which would allow you to also ignore null-properties of a property in this class without adding the attribute to that class as well.

See the below example:

[JsonIgnoreNullValues(Recursive = true)]
class TopLevelClass
{
    public OtherClass NestedProperty {get; set;}
}

class OtherClass
{
    public string Name {get; set;}
    public int Level {get; set;}
}

void Serialize()
{
    var obj = new TopLevelClass 
    {
        NestedProperty = new OtherClass
        {
            Level = 2,
            Name = null
        }
    }

    // Serializing obj (without any options) would result in this json:
    /*
    {
        "NestedProperty": {
            "Level": 2
        }
    }
    */
}

It would probably be much better and simpler to add a new (optional) parameter to IJSRuntime.InvokeAsync of type JsonSerializerOptions but this sadly seems to not be possible.

EDIT: There is a pending feature request for IJSRuntime which I really hope gets accepted. Maybe JsonIgnoreNullValuesAttribute is still a feature which seems worth implementing but just so I'm clear, I would currently not need it if the other feature request passes.

As far as I know this serializer is still worked on so there will be many features added, right? In the roadmap there aren't many features listed that are currently being worked on. Am I looking in the wrong place or are these not publicly available?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions