How to apply JsonExtensionData (Dictionary) to another object with JSON.Net

前端 未结 1 470
栀梦
栀梦 2021-01-20 04:44

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

相关标签:
1条回答
  • 2021-01-20 05:28

    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

    0 讨论(0)
提交回复
热议问题