Nucs / JsonSettings

This library simplifies creating configuration for your C# app/service by utilizing the serialization capabilities of Json.NET to serialize nested (custom) objects, dictionaries and lists as simply as by creating a POCO and inheriting JsonSettings class.
MIT License
76 stars 18 forks source link

Is it possible to call Save() from a child property? #37

Closed henry-js closed 1 year ago

henry-js commented 2 years ago

Given:

public class UserSettings : JsonSettings
{
    public override string FileName { get; set; } = "usersettings.json";
    [NotNull]
    public virtual OpenWeatherSettings OpenWeatherSettings { get; set; } = new()
    {
    };

    public UserSettings()
    {
    }
    public UserSettings(string fileName) : base(fileName)
    {
    }

}

public record class OpenWeatherSettings : IOpenWeatherSettings
{
    public virtual double? Latitude { get; set; }
    public virtual double? Longitude { get; set; }

    public virtual string City { get; set; } = string.Empty;

I would like to be able to call Save() from OpenWeatherSettings

Nucs commented 2 years ago

To be able to serialize OpenWeatherSettings, it needs to be compatible with Json.NET which I think it is, maybe try making OpenWeatherSettings a class (not record) Or you can do this:

public class OpenWeatherSettings : JsonSettings, IOpenWeatherSettings
{
    public override string FileName { get; set; } = "usersettings.json";
    [NotNull]

    public virtual double? Latitude { get; set; }
    public virtual double? Longitude { get; set; }

    public virtual string City { get; set; } = string.Empty;

    public OpenWeatherSettings()
    {
    }
    public OpenWeatherSettings(string fileName) : base(fileName)
    {
    }

}
henry-js commented 2 years ago

The issue is that if I call OpenWeatherSettings.Save() the settings in the parent will be lost because they both have the same filename:

{
  "QueriesCalled": 145,
  "Name": "John Doe",
  "OpenWeatherSettings": {
    "Latitude": null,
    "Longitude": null,
    "City": ""
  }
}

To:

{
  "Latitude": 1.214456,
  "Longitude": -45.4324,
  "City": "Kidderminster"
}

But I would like to call UserSettings.Save() from OpenWeatherSettings.Save()