Search code examples
c#jsonserializersystem.text.json

Is it possible to find unmapped properties in System.Text.Json?


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

Solution

  • 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.