I came across this (seemingly usual) scenario but I could not find a satisfying solution. Maybe someone knows:
For some reason I parse JSON and I allow the user to p
Json.Net does not have a method which will populate an object directly from a standard dictionary. After all, it is a serialization library, not a mapping library. That said, there is a way to make it work without the intermediate serialization/deserialization step.
First, instead of using a Dictionary<string, JToken>
as the container for your [JsonExtensionData]
parameters, use a JObject
. JObject
implements IDictionary<string, JToken>
, so it will still work to catch the extra properties.
class MusterNode
{
...
[JsonExtensionData]
private JObject _extparams;
}
Then, to populate the other object, you just need to create a reader from the JObject
and pass it to JsonSerializer.Populate()
like this:
new JsonSerializer().Populate(_extparams.CreateReader(), obj);
If you have specific serialization settings you need, you can set them directly on the JsonSerializer
prior to calling Populate()
.
Here is a working demo: https://dotnetfiddle.net/kIzc5G