Srinivas
Srinivas

Reputation: 2539

Json in Web.Config AppSettings

I am trying to put some mapping config represented in json:

[{"Name":"xyz","Ids":["456f782d468","c65b4703"]},{"Name":"abc","Ids":["a95fg567","456sdf564"]}]

Is it possible to store a json in appsettings?
I know I can create a custom section in web.config.
But this app may be deployed to Azure Web Apps where appsettings is the only way I see this config can go.

Upvotes: 4

Views: 11651

Answers (5)

Mariusz
Mariusz

Reputation: 964

I used single quotes to store serialized model in the config, then simply deserialized it after reading it from config.

        var serialized = JsonConvert.SerializeObject(yourObject);
        var configFriendlyString = serialized.Replace("\"", "'"); // store it in config file
        var deserialized = JsonConvert.DeserializeObject<YourObjectModel>(configFriendlyString);

Example of how the serialized object looks in the config:

<add key="Categories" value="[{'ID':1,'Name':'All'},{'ID':2,'Name':'Review'}]" />

This way it's easily readable and editable. Note that JsonConvert can deserialize it without need of replacing single quotes back with double quotes.

Upvotes: 0

Eddaye
Eddaye

Reputation: 19

In my web.config, brackets are for using variable like {0} or {1}. So, I need to escape them with double brackets like that:

<add key="ThisIsJson" value="{{&quot;Name&quot;:&quot;xyz&quot;}}"/>

Hope it will help.

Upvotes: 0

Piedone
Piedone

Reputation: 2888

If you use &quot; instead of quote characters then you can store JSON in app settings or connection strings without issues in the Web.config. E.g.:

<add key="ThisIsJson" value="[{&quot;Name&quot;:&quot;xyz&quot;}]"/>

This doesn't need any special processing either, at least with Json.NET.

Upvotes: 1

SledgeHammer
SledgeHammer

Reputation: 7680

Not nicely. The web.config is XML and quotes are not allowed in XML without escaping them to ". Doing that on a JSON still will make it "difficult" to read / maintain. Base64 that serhiyb is one solution, but that will not be maintainable by a person either.

I'd store them as appsettings key/value pairs and then generate the json string at runtime.

If you are 100% the string will never change, then escaping or Base64 is an option.

Upvotes: 3

serhiyb
serhiyb

Reputation: 4833

With your limitations I would just encode it to Base64 string and decode it back when you read it from web.config.

Upvotes: 2

Related Questions