How to apply JsonExtensionData (Dictionary<string, JToken>) to another object with JSON.Net

一个人想着一个人 提交于 2019-12-31 02:43:10

问题


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 provide more key-value pairs than my class has properties. I store the arbitrary ones away like so:

class MusterNode
{
    // some definite property
    public string TypeName { get; set; }

    // takes the rest
    // see https://www.newtonsoft.com/json/help/html/DeserializeExtensionData.htm
    [JsonExtensionData]
    private Dictionary<string, JToken> _extparams;
}

If I deserialize something like

{
   "TypeName": "a",
   "stuff": 3
}

TypeName will be set and my _extparams contains a key "stuff".

For some reason I want to apply that stored data to another (just created) object 'obj' (in fact the parameters were thought for that typename thingy). So I have a Dictionary and an object. Is there a way to 'apply' the dictionary without serializing it first?

My non-satisfying solution is this:

string json = JsonConvert.SerializeObject(_extparams);
JsonConvert.PopulateObject(json, obj);

decorated with some JsonSerializerSettings, this works for me. But it does unnecessary work.


回答1:


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



来源:https://stackoverflow.com/questions/52792214/how-to-apply-jsonextensiondata-dictionarystring-jtoken-to-another-object-wi

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!