1

A webservice (that I do not own/control) returns (as Json) varying amounts of data for calls with different parameters. Some of these data fields are common.

Platform: .NET/C#, with Newtonsoft.Json library.

I cannot define individual classes for each of these variations.

So, I was wondering if there is a way to tell the Newtonsoft.Json Deserialize() methods that I want them to put the remaining Json objects into a particular property -- possibly a Dictionary<string, object> ?

  • 2
    Looks like a duplicate of [How to serialize a Dictionary as part of its parent object using Json.Net](https://stackoverflow.com/q/14893614/3744182) and/or [How to apply JsonExtensionData (Dictionary) to another object with JSON.Net](https://stackoverflow.com/q/52792214/3744182). – dbc Mar 07 '19 at 17:47
  • That's highly unfair, arbitrary and discriminatory. –  Mar 07 '19 at 17:59
  • The accepted answer to the linked duplicate shows how to put unknown JSON values into a `[JsonExtensionData] public Dictionary Y { get; set; }`, which is what your question requires. If you need additional help, you might [edit] your question to explain how the linked answers do not answer your question by providing a [mcve] showing some JSON and c# types into which you need to deserialize the JSON. – dbc Mar 07 '19 at 18:03
  • Your actions are unfair because I did not know about JsonExtensionData (which is the premise for having for the 2nd of your links) and my starting point the same as that of the 1st question. When I search for my problem statement, those are NOT the two results that would come up or make sense in a search result. The solution to a 100 problems may be the same thing. That doesn't mean 99 of them are duplicates of the one. –  Mar 08 '19 at 07:34

1 Answers1

3

There is an attribute available for this called JsonExtensionData. It can be placed on a property with a suitable type to receive excess data:

[JsonExtensionData]
public IDictionary<string, JToken> AdditionalData { get; set; }

Personally, I've used also the following ones - but only for serialization and not deserialization:

[JsonExtensionData]
public IDictionary<string, object> AdditionalData { get; set; }

[JsonExtensionData]
public IDictionary<string, dynamic> AdditionalData { get; set; }
Namoshek
  • 6,394
  • 2
  • 19
  • 31
  • Thank you. I was just going through https://www.newtonsoft.com/json/help/html/DeserializeExtensionData.htm just now. I tried a small sample and ran into Deserialization exceptions :-( Do you have a bigger example of how this is used? My Json would contain simple key/value pairs, dictionaries and even child-objects. –  Mar 07 '19 at 15:16
  • I just tested all 3 variants I described and all are working. See [this dotnetfiddle](https://dotnetfiddle.net/3bfnMC) for an example with `JToken`. – Namoshek Mar 07 '19 at 15:51