Home > database >  C# Replace an array in a JSON file
C# Replace an array in a JSON file

Time:11-24

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?

CodePudding user response:

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

CodePudding user response:

I would use JsonNode (native to .NET) from System.Text.Json

var json = @"{
""exchange"":{
    ""pair_whitelist"": [
          ""EOS3S/USDT"",
          ""ACH/USDT"",
          ""SOC/USDT""]
    }
}";
var node = JsonNode.Parse(json);
node["exchange"]["pair_whitelist"] = new JsonArray("SKM/USDT", "NEW/USDT", "XEC/USDT");

var newJson = node.ToJsonString();
  • Related