Skip to content

Support filtering property names on dictionary deserialization. #79059

@terrajobst

Description

@terrajobst

EDIT See #79059 (comment) for API proposal.

It seems there is currently no way to make JSON documents that reference a schema just deserializa.

Repro

{
    "$schema": "http://example.org/myschema.json",
    "Key1": {
        "V1": 10,
        "V2": "Ten"
    },
    "Key2": {
        "V1": 20,
        "V2": "Twenty"
    }
}
var content = "<json above>";
return JsonSerializer.Deserialize<Dictionary<string, CustomType>>(content);

class CustomType {
    public int V1 { get; set; }
    public string V2 { get; set; }
}

Expected Behavior

It just works. Or, based on JsonSerializerOptions, it could be configured to just work.

Actual Behavior

It causes an exception:

The JSON value could not be converted to CustomType. Path: $.$schema

In order to make it deserializable, the easiest option is to manually remove the schema node from the document:

if (JsonNode.Parse(content) is JsonObject jsonObject)
{
    if (jsonObject.Remove("$schema"))
        content = jsonObject.ToJsonString();
}

The more performant alternative would be to write a custom converter, but that seems like a lot of work. If the root type of the document weren't dictionary but a type I control, then presumably I could work this around by adding a property to my class and decorate it with [JsonPropertyName("$schema")] but that feels equally hacky.

Customer Evidence

It’s not entirely clear to me if this is worth prioritizing. On the one hand, it seems a decent amount of our customers might use JSON schemas (based on this super scientific poll below).

On the other hand, it would only impact customers who use dictionaries as the document type. That combination might be quite rare and may not be be worth handling directly. And based on James’s comments below, JSON.NET never handled that either. I suggest we leave it open for a bit and see what responses we get but my gut feel says cutting seems fine.

A5B403CE-A45D-49BD-9861-9C3D65E3281F

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions