Passing Json information to object constructor when deserializing

不问归期 提交于 2020-03-26 15:13:10

问题


I have a Json file that is composed of nested serialized objects.
When deserializing this file I get my nested object reconstructed as needed, doing the following:

var SomeNestedObjects= JsonConvert.DeserializeObject<SomeNestedObjectsFormat>(File.ReadAllText(@"e:\file.json"));

Now, everything works great because my system has a definition of all these nested object and the JsonConverter is therefore able to create and initialise the lot out of whatever is in that Json file.

What I would like to do though is to have a dummy module that is empty and gets constructed/built/populated at runtime based on what is found in the Json file. Let's take the following Json file as an example, containing 1 module composed of 2 parameters:

{
  "Name": "DummyModule",
  "param1": {
    "Value": 456,
    "Name": "Param1",
    "MinValue": 0,
    "MaxValue": 500
  },
  "param2": {
    "Value": false,
    "Name": "Param2",
    "MinValue": false,
    "MaxValue": true
  }
}

Now, my system has a class Parameter, but my DummyModule class does not know anything about Param1 and Param2. The reason is that this DummyModule can be composed of anything and can change at runtime.

So what I would like to do is to be able to add properties to my DummyModule at runtime when I read my Json. In order to do so, I would need to do some magic within my DummyModule constructor based on that is read out of the Json.
Problem is that I don't know how my constructor can access or be passed information about the Json file. Here is my DummyModule() class:

public class DummyModule
{
    public string Name { get; set; }

    [JsonConstructor]
    public DummyModule()
    {
        // Use Json Object here to create/add my "Param1" and "Param2" properties on the fly
        // ...

        // Something of the sort:       
        foreach (var param in jsonObject)
            CreateProperty(tb, param.FieldName, param.FieldType);
    }
}

回答1:


If your object doesn't have to be DummyModule type, you can use ExpandoObject as your destination type to deserialize the JSON:

The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members.

dynamic myObject = JsonConvert.DeserializeObject<ExpandoObject>(File.ReadAllText(@"e:\file.json"));

Console.WriteLine(myObject.Name);
Console.WriteLine(myObject.Name.GetType());

Console.WriteLine(myObject.param1.Value);
Console.WriteLine(myObject.param1.Value.GetType());

And this would be the output:



来源:https://stackoverflow.com/questions/60547127/passing-json-information-to-object-constructor-when-deserializing

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