I want to import Json file into a class
This is a toy Json file I have
{
"a": {
"Name": "foo",
"Age": 2
},
"b": {
"Name": "bar",
"Age": 3
}
}
I import the Json files inside the class Params using the following code. Then I use this information to create two persons, a and b
public class Params
{
JObject m_params;
Params()
{
using (StreamReader file = File.OpenText(filename))
using (JsonTextReader reader = new JsonTextReader(file))
{
m_params = (JObject)JToken.ReadFrom(reader);
}
Person Person1 = new Person(m_params["a"]);
Person Person2 = new Person(m_params["b"]);
}
}
Now here's the implementation of Person
public class Person
{
string Name;
int Age;
Person(JToken data)
{
Name = data["Name"];
Age = data["Age"];
}
}
This works, but I feel it should be an easier way to do that.
If instead of just having name
and age
I have 100 parameters, the initialization of Person will be 100 lines of code.
If there a way of directly assigning data["Name"] to Person.Name and do the rest for all the parameters of Person?
How could my importing be improved, so when I have a lot of people with a lot of fields I can import everything easily?