1

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?

  • It is a very common operation called "Deserialization". I Don't know much about C# so I'll comment instead of answering. A simple google search should do the trick. Beware, your question might be flagged a duplicate of this one : https://stackoverflow.com/questions/7895105/deserialize-json-with-c-sharp – NRagot Feb 10 '22 at 14:52

2 Answers2

1

It looks like you are using the Newtonsoft.JSON NuGet-Package.

If so, there is a JsonConvert-Class that exposes the DeserializeObject<T>-Method to archive this.

The tricky bit here is that your Persons are contained in a Dictionary, so the following code should work for you:

public class Params
{
    Params()
    {
        string json = File.ReadAllText(filename);
        
        var dictionary = JsonConvert.DeserializeObject<Dictionary<string, Person>>(json);
        var person1 = dictionary["a"];
        var person2 = dictionary["b"];
    }   
}


public class Person
{
    string Name;
    int Age;
    // Remove the constructor or add a parameterless one
}

0

You can simply deserialize the objects directly like this:

public class Params
{
    Person a;
    Person b;
}

public class Person
{
    string Name;
    int Age;
}

var jsonText = File.ReadAllText("config.json");
var people = JsonSerializer.Deserialize<Params>(jsonText);