Edit values in appconfig.json using C# - c#

Is there any way to edit value inside appsetting.json using controller?
So, here is the appsetting.json:
{
"Person": {
"p1": "test1",
"p2": "test2",
"p3": "test3"
}
}
and this is the class:
public class
{
public string p1{ get; set; }
public string p2{ get; set; }
public string p3{ get; set; }
}
I do some research but no clue. I just find how to read the value of appsetting.json. What I want is to edit the value from controller and save it.

Try
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
config.AppSettings.Settings["p1"].Value = "test1";
config.AppSettings.Settings["p2"].Value = "test2";
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");

Related

Parsing json. Field could be plain text and object

Shortly, I'm trying to create some web-API-application and I'm parsing telegram data and I am faced up with a problem.
When I get all the JSON, I see that the program can't parse it because some field(text) couldn't resolve the object(code snip below). I'm thinking about creating a custom JSON converter(that's annoying, so that's the reason why I'm here), but maybe I just don't know how to do it correctly.
Here are examples:
{
"text": "SOME VERY VERY VERY PRIVATE INFORMATION",
},
AND
{
"text": [
{
"type": "link",
"text": "SOME VERY VERY VERY PRIVATE LINK :D(probably, onlyfans)"
}
],
}
I usually use a JsonConstructor in this case. You don't need to pass all properties into the constructor, you can pass only the properties that cause a problem.
using Newtonsoft.Json;
Data data = JsonConvert.DeserializeObject<Data>(json);
public class Data
{
public List<Text> text { get; set; }
[JsonConstructor]
public Data(JToken text)
{
if (text.Type == JTokenType.String)
this.text = new List<Text> { new Text { text = (string)text } };
else this.text = text.ToObject<List<Text>>();
}
}
public class Text
{
public string type { get; set; }
public string text { get; set; }
}
I would use system.text.json More info here
and here
public class Data
{
[JsonPropertyName("text")]
public IEnumerable<TextInformation> TextInformations{ get; set; }
}
public class TextInformation
{
[JsonPropertyName("type")]
public string Type { get; set; }
[JsonPropertyName("text")]
public string Text { get; set; }
}
and use it like this
var text = JsonSerializer.Deserialize<Data>(jsonString)

Read from appsettings.json config file

I have the following config in my appsettings.json File
{
"AppSettings": {
"MainUser": {
"Name": "Urs",
"Surname": "Barandun",
"SesstionTimeInMin": "30",
}
},
And I'd like to create a custom configuration class and bind it. Eg:
MainUserConfiguration mainUserConfiguration = new MainUserConfiguration();
var configSection = config.GetSection("MainUserConfiguration");
configSection.Bind(mainUserConfiguration);
But, my code does not work. :/
Based on what you've provided, your appsettings file and the nested JSON for your configuration don't match up. A typical ASP.NET Core appsettings.json doesn't have a nested element called "AppSettings", and further you're getting a configuration section called "MainUserConfiguration" while your actual JSON just names that section "MainUser".
appsettings example:
{
"MyFirstClass": {
"Option1": "some string value",
"Option2": 42
},
"MySecondClass": {
"SettingOne": "some string value",
"SettingTwo": 42
}
}
In your code:
public class MyFirstClass
{
public string Option1 { get; set; }
public int Option2 { get; set; }
}
public class MySecondClass
{
public string SettingOne { get; set; }
public int SettingTwo { get; set; }
}
In your Startup.cs (presuming that's where you're accessing it with a defined Configuration object:
var myFirstClass = Configuration.GetSection("MyFirstClass").Get<MyFirstClass>();
var mySecondClass = Configuration.GetSection("MySecondClass").Get<MySecondClass>();
Console.WriteLine($"The answer is always {myFirstClass.Option2}");

Return JSON from API method

I am using ASP.net Core web api (c#) here
I have a JSON string as:
{
"userId":321,
"account":"new
"fname":"Adam",
"lname":"Silver"
"features":[
{
"available":true,
"status":open,
"admin":false
}
]
}
I want to test this data in my angular code so wanted to hardcode this into my API; then I want my API to return this back. What I am finding it hard is how to return this. Shall I return this as a string or need to parse it?
I have this method in my API:
[HttpGet]
public ActionResult<IEnumerable<string>> Get()
{
return new string[] { "value1", "value2" };
}
Do I need to represent this into string or parse it someway?
Your JSON is invalid. We need to correct it. JSONLint can be helpful for that. I took your JSON and corrected the syntax errors until I got this:
{
"userId": 321,
"account": "new",
"fname": "Adam",
"lname": "Silver",
"features":[
{
"available": true,
"status": "open",
"admin": false
}
]
}
Then I need to generate a C# class structure to represent this JSON. I could manually create it, but the excellent json2csharp.com can generate it for me quickly. I fed this JSON into and received the following classes back:
public class Feature
{
public bool available { get; set; }
public string status { get; set; }
public bool admin { get; set; }
}
public class RootObject
{
public int userId { get; set; }
public string account { get; set; }
public string fname { get; set; }
public string lname { get; set; }
public List<Feature> features { get; set; }
}
I put these class definitions into my application. Then I need to modify my action method to create an instance of this RootObject class (you should change the name to actually match what it's intended for).
[HttpGet]
public ActionResult<RootObject> Get()
{
// Create an instance of our RootObject and set the properties
var myRootObject = new RootObject();
myRootObject.userId = 321;
myRootObject.account = "new";
myRootObject.fname = "Adam";
myRootObject.lname = "Silver";
myRootObject.features = new List<Feature>();
// Create an instance of a feature and set its properties
var feature = new Feature();
feature.available = true;
feature.status = "open";
feature.admin = false;
// Add the new feature to the features collection of our RootObject
myRootObject.features.Add(feature);
// Return the instance of our RootObject
// The framework will handle serializing it to JSON for us
return myRootObject;
}
Note that I changed the signature of your method. I made it no longer accept an IEnumerable because it wasn't clear why you had that. And I changed it to return an ActionResult after checking Microsoft's documentation.
Hi Please find correct JSON format for above one:
{
"userId": 321,
"account": "new",
"fname": "Adam",
"lname": "Silver",
"features": [{
"available": true,
"status": "open",
"admin": false
}]
}
you can use below class in your web API to pass respective data
public class Feature
{
public bool available { get; set; }
public string status { get; set; }
public bool admin { get; set; }
}
public class RootObject
{
public int userId { get; set; }
public string account { get; set; }
public string fname { get; set; }
public string lname { get; set; }
public List<Feature> features { get; set; }
}
then at the end, while returning data, convert the respective class object into JSON by serializing that into JSON format.
Hope it will fulfill your requirement.
Putting the comments into an answer:
If you are using ActionResult, I'll assume you are using asp.net mvc. What you want is JsonResult.
[HttpGet]
public JsonResult Get()
{
return new JsonResult
{
Data = new
{
userId = 321,
account = new
{
fname = "Adam",
lname = "Silver",
features = new object[]{
new
{
available = true,
status = "open",
admin = false
}
}
}
},
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}

Cannot create instance of type 'System.String'

I try to get my section from appsettings.json, and then bind it to the intance of MongoSettings class, but I have an exception which is:
"Cannot create instance of type 'System.String' because it is missing
a public parameterless constructor."
It is strange, because I'm using the same method to get jwt settings.
Please take a look:
var jwtSettings = Configuration.GetSection("jwt").Get<JwtSettings>(); //it works
var mongoSettings = Configuration.GetSection("mongo").Get<MongoSettings>(); //it doesn't
appsettings.json
"Jwt": {
"issuer" : "localhost:5000",
"expiryMinutes" : 60,
"key" : "das##4SD120847#12313"
},
"Mongo": {
"connection:" : "mongodb://localhost:27017",
"database" : "MemoTime"
}
MongoSettings:
public class MongoSettings
{
public string Connection { get; set; }
public string Database { get; set; }
}
JwtSettings:
public class JwtSettings
{
public string Key { get; set; }
public string ValidIssuer { get; set; }
public int ExpiryMinutes { get; set; }
}
As you can see, both clasess and sections in app settings looks similarly, so why getting settings for mongo does not work?
You Issue is in Json there is extra colon ":" that why it is giving error
Valid Json Data.
"Jwt":
{
"issuer": "localhost:5000",
"expiryMinutes": 60,
"key": "das##4SD120847#12313"
},
"Mongo":
{
"connection": "mongodb://localhost:27017",
"database": "MemoTime"
}

Deserialize nested JSON into Dictionary, string and class

I have a JSON that I'd like to DeserializeObject into an outerDictionary with innerDictionary and innermostClass as so:
var entityMap = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, fieldClass>>>(File.ReadAllText("map.json"));
However, the innerDictionary may have a string:string instead of string:innerMostClass.
{
"Client": {
"__class__": "contact",
"ClientId": {
"__field__": "new_ndisclientid",
"__type__": "string"
},
"GivenName": {
"__field__": "firstname",
"__type__": "string"
},
},
"Case": {
"__class__": "contact",
"CaseId": {
"__field__": "new_ndiscaseid",
"__type__": "string"
}
}
}
Is there a way to do this? I don't want to make all of it into Classes.
Is it possible to do this with a custom JsonConverter?
EDIT: Renamed classname to entityName for clarity. ClientId and GivenName would be deserialized into fieldClasses.
You can use dynamic or object instead of inner class
var json =
"{\r\n\t\"Client\": {\r\n\t\t\"__entityName__\": \"contact\",\r\n\r\n\t\t\"ClientId\": {\r\n\t\t\t\"__field__\": \"new_ndisclientid\",\r\n\t\t\t\"__type__\": \"string\"\r\n\t\t},\r\n\t\t\"GivenName\": {\r\n\t\t\t\"__field__\": \"firstname\",\r\n\t\t\t\"__type__\": \"string\"\r\n\t\t}\r\n\t}\r\n}";
var deserialized = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, dynamic>>>(json);
List<object> values = deserialized.SelectMany(result => result.Value).Cast<object>().ToList();
If you want separate inner class
public class Client
{
public string __entityName__ { get; set; }
public Dictionary<string, string> ClientId { get; set; }
public Dictionary<string, string> GivenName { get; set; }
}
var deserializedWithClass = JsonConvert.DeserializeObject<Dictionary<string, Client>>(json);
Deserialize nested JSON into Class. not on dictionary based but it's useful.
Step 01: open the link https://jsonformatter.org/json-parser
Step 02: copy the down contents.
{
"Client": {
"__class__": "contact",
"ClientId": {
"__field__": "new_ndisclientid",
"__type__": "string"
},
"GivenName": {
"__field__": "firstname",
"__type__": "string"
}
},
"Case": {
"__class__": "contact",
"CaseId": {
"__field__": "new_ndiscaseid",
"__type__": "string"
}
}
}
Step 03: Open above link. copy contents and past in to left side and click on to JSON Parser button. Look like below image.
Step 04: Click on download button. Downloading the jsonformatter.txt file. Successfully download the file as jsonformatter.txt.
Step 05: Copy step 02 content and open url https://json2csharp.com/.Copy contents and past in to left side and click on to Convert button. Look like below image.
Step 06: In Scripting.
(A) Create myRootClass.cs file and copy and past down contents to your file.[[System.Serializable] it's used in unity 3d software c# scripting]
[System.Serializable]
public class myRootClass
{
[System.Serializable]
public class ClientId
{
public string __field__ { get; set; }
public string __type__ { get; set; }
}
[System.Serializable]
public class GivenName
{
public string __field__ { get; set; }
public string __type__ { get; set; }
}
[System.Serializable]
public class Client
{
public string __class__ { get; set; }
public ClientId ClientId { get; set; }
public GivenName GivenName { get; set; }
}
[System.Serializable]
public class CaseId
{
public string __field__ { get; set; }
public string __type__ { get; set; }
}
[System.Serializable]
public class Case
{
public string __class__ { get; set; }
public CaseId CaseId { get; set; }
}
[System.Serializable]
public class Root
{
public Client Client { get; set; }
public Case Case { get; set; }
}
}
(B) Read the jsonformatter.txt file.
// Read entire text file content in one string
string textFilePath = "C:/Users/XXX/Downloads/jsonformatter.txt";//change path
string jsontext = System.IO.File.ReadAllText(textFilePath);
Debug.Log("Read Json"+jsontext);// used Console.Writeline
(C) Convert string into C# and show the data.
Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(jsontext);
var client = myDeserializedClass.Client;
Debug.Log("client.__class__ :- "+client.__class__); //used Console.Writeline
Debug.Log("client.ClientId.__field__ :- "+client.ClientId.__field__);// used Console.Writeline
Debug.Log("client.GivenName.__field__ :- "+client.GivenName.__field__);// used Console.Writeline

Categories