Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# The node must be of type 'JsonArray'

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?

like image 496
Nodo Avatar asked Nov 29 '25 01:11

Nodo


1 Answers

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
}
like image 123
Mihal By Avatar answered Dec 01 '25 16:12

Mihal By