3

Is it possible to find unmapped properties with the System.Text.Json.JsonSerializer?

I'm accessing an API which returns an array of documents. I want to know if there is a way to know if there is an property in the json document which is not mapped by my C# type. At best a method that returns a list of unmapped properties.

Example

JSON Document

{
    "docs": [
        {
            "foo": "a",
            "bar": "b",
            "baz": "c",
        }
    ]
}

C# types

public class Wrapper 
{
    [JsonPropertyName("docs")]
    public List<MyDocument> Documents { get; set; }
}

public class MyDocument 
{
    [JsonPropertyName("foo")]
    public string Foo { get; set; }

    [JsonPropertyName("baz")]
    public string Baz { get; set; }
}

Parser

using System.Text.Json;

var body = "{ ... }";
var documents = JsonSerializer.Deserialize<Documents>(body);

List<JsonElement> unmappedProperties 
    = JsonSerializer.FindUnmappedProperties<Document>(body);
boop
  • 7,413
  • 13
  • 50
  • 94
  • Looks like a duplicate of [Is it possible to catch somehow the remainder of JSON data that didn't match any POCO properties while deserializing?](https://stackoverflow.com/q/63227109/3744182), agree? – dbc Jun 06 '21 at 21:16

1 Answers1

6

You could use [JsonExtensionData], for example:

public class MyDocument 
{
    [JsonPropertyName("foo")]
    public string Foo { get; set; }

    [JsonPropertyName("baz")]
    public string Baz { get; set; }

    [JsonExtensionData]
    public Dictionary<string, object> ExtensionData { get; set; }
}

The property "bar" will be serialized to the ExtensionData property.

You need .NET Core 3+ or .NET 5+ (or .NET framework 4.6.1 / NET Standard 2.0, see comment of Jimi)

See How to handle overflow JSON with System.Text.Json

To find all unmapped properties you need to add the property with [JsonExtensionData] to all classes that get serialized. Also you need to loop over it (maybe with reflection). It's a bit cumbersome, but it works.

Julian
  • 33,915
  • 22
  • 119
  • 174