Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find JArray and add JObject

Tags:

c#

json.net

How do you find a JArray named "response" and add a New JObject?

var json = new JObject();
json.Add(new JProperty("response", new JArray()));

using (var reader = dbCommand.ExecuteReader()) {
    while (reader.Read()) {
        json.GetValue("response").AddAfterSelf( // throws exception
            new JObject(
                new JProperty("id", reader.GetString(0)),
                new JProperty("val", reader.GetString(1))
            )
         );
    }
}
like image 616
JorgeeFG Avatar asked Feb 01 '26 18:02

JorgeeFG


1 Answers

First off, always include information about your error. This helps your fellow peers assist you.

The error states that 'JProperty cannot contain multiple values'.

All you need to do is update two lines:

json.Add("response", new JArray());  // simplified

and

((JArray)json.GetValue("response")).Add(

The casting of json.GetValue('response') to JArray gives you access to its Add method and fixes the error.

Final Code:

var json = new JObject();
json.Add("response", new JArray());

using (var reader = dbCommand.ExecuteReader()) {
    while (reader.Read()) {
        ((JArray)json.GetValue("response")).Add( // <- add cast
            new JObject(
                new JProperty("id", reader.GetString(0)),
                new JProperty("val", reader.GetString(1))
            )
         );
    }
}
like image 104
Sean Avatar answered Feb 04 '26 11:02

Sean



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!