How to serialize a Dictionary as part of its parent object using Json.Net

If you’re using Json.Net 5.0.5 or later and you’re willing to change the type of your dictionary from Dictionary<string, string> to Dictionary<string, object>, then one easy way to accomplish what you want is to add the [JsonExtensionData] attribute to your dictionary property like this:

public class Test
{
    public string X { get; set; }

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

The keys and values of the marked dictionary will then be serialized as part of the parent object. The bonus is that it works on deserialization as well: any properties in the JSON that do not match to members of the class will be placed into the dictionary.

Leave a Comment