Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# Replace an array in a JSON file

I’m trying to replace an array in a JSON file using C# .net 6.0

There is such a JSON file:

{
...
"exchange":{
...
"pair_whitelist": [
      "EOS3S/USDT",
      "ACH/USDT",
      "SOC/USDT"]
...
}
...
}

I want to replace this "pair_whitelist" array with another array

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"pair_whitelist": [
      "SKM/USDT",
      "NEW/USDT",
      "XEC/USDT"]

How should I do it?

My attempt was as follows

public static dynamic GetJSONFromFile_dynamic(string path)
{
 var data = File.ReadAllText(path);
 return JsonSerializer.Deserialize<ExpandoObject>(data);
}
...
var config = GetJSONFromFile_dynamic(path_to_JSON_file);
dynamic a = config.exchange.pair_whitelist;

But I got the following error: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ”System.Text.Json.JsonElement’ does not contain a definition for ‘pair_whitelist”

How to change the value of the pair_whitelist array?

>Solution :

You can try JObject.Parse() to parse Json file and then replace the value of an array

JObject jObject = JObject.Parse(File.ReadAllText(path_to_JSON_file));

if(jObject["exchange"]?["pair_whitelist"] != null) //Check key exists before update
     jObject["exchange"]["pair_whitelist"] = ["Stack", "Overflow"];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading