Home > database >  .net core not able to read object out of appsettings.json
.net core not able to read object out of appsettings.json

Time:07-27

My dotnetcore application has a problem reading this object out of the appsettings.json:

  "image": {
    "ImagePresets": {
      "SearchListing"    : {"Width": 415, "Height": 220, "Fit": true},
      "PropertyPage"     : {"Width": 650, "Height": 350, "Fit": true},
      "Large"            : {"Width": 910, "Height": 650, "Fit": true},
      "FeaturedLocation" : {"Width": 272, "Height": 296, "Fit": true}
    }
  },

here is the object I'm trying to deserialize it to:

public class ImagePresets
{
    public Preset SearchListing { get; set; }
    public Preset PropertyPage { get; set; }
    public Preset Large { get; set; }
    public Preset FeaturedLocation { get; set; }

    public ImagePresets()
    {
        FeaturedLocation = SearchListing = Large = PropertyPage = new Preset();
    }

}
    public class Preset
{
    int Width { get; set; }
    int Height { get; set; }
    bool Fit { get; set; }
}

and this is how I am trying to read it:

ImagePresets _presets = _config.GetSection("image:ImagePresets").Get<ImagePresets>();

When I try executing _config.GetSection("image:ImagePresets").GetChildren() I do get the KeyValuePairs, but deserializing always returns empty values like:

Fit [bool]:
false
Height [int]:
0
Width [int]:
0

What am I doing wrong? Any help would be appreciated.

CodePudding user response:

It is simply because the properties of Preset is not public. This works

public class Preset
{
    public int Width { get; set; }
    public int Height { get; set; }
    public bool Fit { get; set; }
}

According to the documentation:

An options class:

  • Must be non-abstract with a public parameterless constructor.
  • All public read-write properties of the type are bound.

CodePudding user response:

El problema es que las propiedades de la clase Presset con privadas, deberían ser publicas para que puedan ser accesibles.

    public class Preset
{
    public int Width { get; set; }
    public int Height { get; set; }
    public bool Fit { get; set; }
}

Resultado con propiedades publicas

CodePudding user response:

If I am not wrong, You get get values like following code:

public class ClassName{

    public ClassName(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    YourClass YourMethod() {
        return Configuration["image:ImagePresets:SearchListing"];
    }
}

  • Related