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

"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"];

Leave a Reply