Deserialize json with known and unknown fields

c#, json, json.net

Solution

An even easier option to tackling this problem would be to use the JsonExtensionDataAttribute from JSON .NET

public class MyClass
{
   // known field
   public decimal TaxRate { get; set; }

   // extra fields
   [JsonExtensionData]
   private IDictionary<string, JToken> _extraStuff;
}

There's a sample of this on the project blog here

UPDATE Please note this requires JSON .NET v5 release 5 and above

Problem

Given following json result: The default json result has a known set of fields: ``` { "id": "7908", "name": "product name" } ``` But can be extended with additional fields (in this example `_unknown_field_name_1` and `_unknown_field_name_2`) of which the names are not known when requesting the result. ``` { "id": "7908", "name": "product name", "_unknown_field_name_1": "some value", "_unknown_field_name_2": "some value" } ``` I would like the json result to be serialized and deserialized to and from a class with properties for the known fields and map the unknown fields (for which there are no properties) to a property (or multiple properties) like a dictionary so they can be accessed and modified. ``` public class Product { public string id { get; set; } public string name { get; set; } public Dictionary<string, string> fields { get; set; } } ``` I think I need a way to plug into a json serializer and do the mapping for the missing members myself (both for serialize and deserialize). I have been looking at various possibilities: - json.net and custom contract resolvers (can't figure out how to do it) - datacontract serializer (can only override onserialized, onserializing) - serialize to dynamic and do custom mapping (this might work, but seems a lot of work) - let product inheriting from DynamicObject (serializers work with reflection and do not invoke the trygetmember and trysetmember methods) I'm using restsharp, but any serializer can be plugged in. Oh, and I cannot change the json result, and this or this didn't help me either. Update: This looks more like it: http://geekswithblogs.net/DavidHoerster/archive/2011/07/26/json.net-custom-convertersndasha-quick-tour.aspx

Original source