Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 尝试从Json对象C提取值时出错#_C#_Json_Object_Json.net - Fatal编程技术网

C# 尝试从Json对象C提取值时出错#

C# 尝试从Json对象C提取值时出错#,c#,json,object,json.net,C#,Json,Object,Json.net,我有一个Json字符串,如下所示,这只是一个小片段。引号中的数字是一个Unix时间,我需要使用它来迭代每个对象 { "result": { "1534860000": [ "1534860000", 19, 41 ], "1534863600": [ "1534863600", 11, 16 ], "1534867200": [ "1534867200",

我有一个Json字符串,如下所示,这只是一个小片段。引号中的数字是一个Unix时间,我需要使用它来迭代每个对象

{
  "result": {
    "1534860000": [
      "1534860000",
      19,
      41
    ],
    "1534863600": [
      "1534863600",
      11,
      16
    ],
    "1534867200": [
      "1534867200",
      2,
      5
    ]
  }
}
但是当我试图提取数组中的数据时,我得到了一个错误:

System.InvalidOperationException:'无法访问Newtonsoft.Json.Linq.JProperty上的子值。'

代码:


有人能解释一下我遗漏了什么吗?

在柯克·拉金的帮助下,我想我会发布一段代码片段

JObject jsonObj = JObject.Parse(response);

int hour = 0;
string unixTime = Helpers.ConvertToUnix(yesterday.AddHours(hour)).ToString();

var array = jsonObj["result"][unixTime];

它现在返回数组的内容。

如果我们稍微简化您的示例代码以删除
unixTime
元素(现在让我们对其进行硬编码),我们将得到以下结果:

JObject jsonObj = JObject.Parse(response);
string unixTime = "1534860000";
在这个阶段,我们有
jsonObj
,它引用JSON对象的根,并且有一个
result
属性。在此处重复您的
foreach
,了解上下文:

foreach (var obj in jsonObj["result"])
{
    var array = obj[unixTime]; //here is where the error occurs
}
最后得到的是引用
result.1534860000的JSON路径的
obj
。问题是,您正在这个JSON路径(
result.1534860000.1534860000
)上查找一个不存在的属性
1534860000

您可以直接获取值,如下所示:

var array = obj["result"][unixTime]

当然,这需要进行一些错误检查以确保路径存在,等等,但它说明了这一点。

在这个特定实例中,unix时间与json的第一个条目完全相同,例如“1534860000”
var array = obj["result"][unixTime]