mardi 21 juillet 2020

How to merge a JSON object with the current class

I am trying to make a class that can save and load its own members from a json file automatically.

What I want to know is if NewtonSoft.Json provides a method to do that already or if I will have to use reflection.

class Settings
{
    // this is my setting
    public bool dostuff = false;

    public int maxstuff = 123;

    public string namestuff = "foo";

    List<string> arrayofstuff = new List<string>();



    private string fileLocation;

    public Settings(string fileLocation)
    {
        this.fileLocation = fileLocation;
    }

    public void LoadSettings()
    {
        string content = System.IO.File.ReadAllText(this.fileLocation);

        JObject data = JObject.Parse(content);


        // Normally I would have a sub class that contains all the settings
        // I would create an instance of it. Serialize into a JObject
        // Then merge with the data object.
        // Then use ToObject to assign the updated values

        myDuplicateJObject.Merge(data, new JsonMergeSettings
        {
            MergeArrayHandling = MergeArrayHandling.Union
        });

        // However I need to apply it to the current object which is "this"
        
    }

    public void SaveSettings()
    {
        System.IO.File.WriteAllText(this.fileLocation, JsonConvert.SerializeObject(this));
    }
}

The only two ways I can currently think of to solve this would be to use reflection to try and merge a duplicate copy of my class or to make a sub class that contains all the settings and just use that as a member.





Aucun commentaire:

Enregistrer un commentaire