Home > Mobile >  How to use Options pattern to bind Json value as a string from appsettings.json file
How to use Options pattern to bind Json value as a string from appsettings.json file

Time:06-27

Im building a Web-Api. How do I use the Options pattern to bind a json string value from my appsettings.json. The value in my appsettigs.json file is an escaped json string as shown below (this has to be a json string).

The formatted Json that is saved as a string in my appsettings.json file looks like this

 [
    {
        "Item": "Bread",
        "Code": "Br"
    },
    {
        "Item": "Milk",
        "Code": "Mk"
    }
]

My appsettings.json file with escaped json string

{

    "MappingCodes": {
        "SystemOne": "[{\"Item\":\"Bread\",\"Code\":\"Br\"},{\"Item\":\"Milk\",\"Code\":\"Mk\"}]"
    }

}

I have a MappingCode.cs class (to bind the json string) and a Product.cs class (to represent json string value)

public class MappingCode
{
    public string SystemOne{ get; set; }
}

public class Product
{
    public string Item{ get; set; }
    public string Code{ get; set; }
}

How do i inject a collection of the Product class from the StartUp class so im able to use it something like this

public class MyClass
{
   public MyClass(IOptions<IList<Product>> products){
   {
      var prods = products.Value;
   }
}

CodePudding user response:

add this code to your startup (or program if you use)

services.Configure<MappingCode>(configuration
                    .GetSection("MappingCodes"));

services.AddScoped<MyClass>();

and code

public class MyClass
{
   private readonly List<Product> _products;

    public MyClass(IOptions<MappingCode> mappingCode)
    {
        _products = JsonConvert.DeserializeObject<List<Product>>(mappingCode.Value.SystemOne);
    }
}

if you turn escape string into string in appsettings, you will not need to deserialize, so I recommend

"MappingCodes":{"SystemOne":[{"Item":"Bread","Code":"Br"},{"Item":"Milk","Code":"Mk"}]}

CodePudding user response:

I had written a detail article on same topic some time back.

have a look. hope it will be useful

https://medium.com/@niteshsinghal85/configuration-change-detection-with-ioptionmonitor-in-asp-net-core-e26b71cfdb2f

  • Related