1

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?

2 Answers 2

3

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"];
Sign up to request clarification or add additional context in comments.

Comments

2

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();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.