How can I get the length of a JSON Array I get using json.net in C#? After sending a SOAP call I get a JSON string as answer, I use json.net to parse it.

我得到的json示例:

{"JSONObject": [
    {"Id":"ThisIsMyId","Value":"ThisIsMyValue"},
    {"Id":"ThisIsMyId2","Value":"ThisIsMyValue2"}
]}

我解析它并将其写入控制台:

var test = JObject.Parse (json);
Console.WriteLine ("Id: {0} Value: {1}", (string)test["JSONObject"][0]["Id"], (string)test["JSONObject"][0]["Value"]);

This works like a spell, only I don't know the length of the JSONObject, but I need to do it in a for loop. I only have no idea how I can get the length of test["JSONObject"]

But something like test["JSONObject"].Length would be too easy I guess :(..

推荐答案

You can cast the object to a JArray and then use the Count property, like so:

JArray items = (JArray)test["JSONObject"];
int length = items.Count;

然后可以按如下方式循环项目:

for (int i = 0; i < items.Count; i++)
{
    var item = (JObject)items[i];
    //do something with item
}

According to Onno (OP), you can also use the following:

int length = test["JSONObject"].Count();

However, I have not personally confirmed that this will work

Json相关问答推荐

基于两个条件替换扁平化的SON中的值

当由.sh脚本执行时,AWS查询字符串不会提取任何数据

使用 JSON 和相对日期设置日历视图中 SharePoint 列表项的背景 colored颜色 格式

JOLT分裂和数组数据

jq 中的整个单词匹配

使用 jq 将消息转换为数组

如何在 wso2 中组合 2 个 json 有效负载?

在 Perl Mojolicious 中呈现 JSON 时防止转义字符

JSON.NET 中特定对象的自定义转换

如何使用 gson 调用默认反序列化

一起使用 Argparse 和 Json

在 JSON API Wordpress 上启用 CORS

如何从Typescript 中的json响应中获取日期对象

在 Rails 中使用 JSON 创建嵌套对象

如何使用 LWP 发出 JSON POST 请求?

有必要清理 JSON 吗?

Jsonpath 与 Jackson 或 Gson

有没有办法使用 Jackson 将 Map 转换为 JSON 表示而不写入文件?

如何在 Rails 模型中验证字符串是否为 json

java.lang.BootstrapMethodError:调用站点#4 bootstrap 方法的异常,初始化 retrofit 时