简体   繁体   English

找到JArray并添加JObject

[英]Find JArray and add JObject

How do you find a JArray named "response" and add a New JObject? 你如何找到一个名为“响应”的JArray并添加一个新的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))
            )
         );
    }
}

First off, always include information about your error. 首先,始终包含有关错误的信息。 This helps your fellow peers assist you. 这有助于您的同伴帮助您。

The error states that 'JProperty cannot contain multiple values'. 该错误指出'JProperty不能包含多个值'。

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. 将Json.GetValue('response')转换为JArray可以访问其Add方法并修复错误。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM