I have a static class with static fields and a json.
I can deserialize the json into a dynamic object, so I have all the fields and they match exactly the static fields in the class.
How can I use reflection to enumerate the fields and copy the values from the dynamic class into the static class fields?
I can't change the architecture, make it a singleton, etc; it's shared code and the class is going to remain static since it's globally shared settings object used by a shared library.
The solution needs to use reflection since the class evolves over time with new members. Otherwise I could have written a custom deserializer.
Adding more details, but there is really not much:
I have this static class:
static class A
{
static int I;
static string S;
}
and a json matching the fields exactly:
{
"I" : 3,
"S" : "hello"
}
var Data = JsonConvert.Deserialize<dynamic>(...);
I would like to initialize the static fields of class A with the values I deserialized from the json, into a dynamic object.
Another edit:
I came up with something similar to what David wrote, but this is less efficient since I use the deserializer to convert types, so David's solution is better.
here's what I came up with:
foreach (var Destination in typeof(Settings).GetProperties())
{
var Name = Destination.Name;
var T = Destination.PropertyType;
var Value = JsonConvert.DeserializeObject("\"" + JT[Name] + "\"", T);
Destination.SetValue(null, Value);
}