Reputation: 5981
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))
)
);
}
}
Upvotes: 3
Views: 7494
Reputation: 398
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))
)
);
}
}
Upvotes: 3