I am trying to add an empty Json object "d" in JsonNode as array, manually adds "c" without error, but in loop compiler throws an exception The node must be of type 'JsonArray'
string jsonData = JsonSerializer.Serialize("{\"a\":\"55\",\"b\":\"66\"}");
var jsonNode = JsonNode.Parse(jsonData);
JsonNode jsonNodeEmpty = JsonNode.Parse("{}");
jsonNode["c"] = jsonNodeEmpty; // adding manually no error
foreach (var item in jsonNode.AsArray())
{
jsonNode["d"] = jsonNodeEmpty; // throws an exception The node must be of type 'JsonArray'
}
I tried also new JsonArray(jsonNodeEmpty); instead of jsonNodeEmpty in loop but still same error: Unhandled exception. System.InvalidOperationException: The node must be of type 'JsonArray'
Any ideas?
You JsonNode is not array, if you need look JObject elements try this:
var jsonNode = JsonNode.Parse("{\"a\":\"55\",\"b\":\"66\"}");
JsonNode jsonNodeEmpty = JsonNode.Parse("{}");
jsonNode["c"] = jsonNodeEmpty; // adding manually no error
foreach (var item in jsonNode.AsObject())
{
var i=item;
var jsonNodeEmptyNew = JsonNode.Parse("{}");
// jsonNode["d"] = jsonNodeEmptyNew; you don't modify collection in foreach
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With