Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.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# 在C中迭代JSON数组_C#_Json_Loops_Json.net_Json Deserialization - Fatal编程技术网

C# 在C中迭代JSON数组

C# 在C中迭代JSON数组,c#,json,loops,json.net,json-deserialization,C#,Json,Loops,Json.net,Json Deserialization,我试图弄清楚如何循环一些JSON数据,将其插入数据网格,作为事件日志。然而,试图解析JSON让我头疼 我正在尝试使用Newtonsoft提供的JSON.NET JSON字符串如下所示: { "result" : "ok", "response" : { "first" : 0, "count" : 190, "now" : 1509822169, "events" : [ { "index" : 0, "ti

我试图弄清楚如何循环一些JSON数据,将其插入数据网格,作为事件日志。然而,试图解析JSON让我头疼

我正在尝试使用Newtonsoft提供的JSON.NET

JSON字符串如下所示:

{
    "result" : "ok",
    "response" : {
    "first" : 0,
    "count" : 190,
    "now" : 1509822169,
    "events" : [
    {
        "index" : 0,
        "time" : 1509815973,
        "name" : "SessionCreated",
        "attributes" : {}
    },
    {
        "index" : 1,
        "time" : 1509815973,
        "name" : "PlayerJoined",
        "refid" : 32896,
        "attributes" : {}
        "Name" : "Dealman",
        "SteamId" : "76561197986562417"
    },
    {
        "index" : 2,
        "time" : 1509815973,
        "name" : "Authenticated",
        "refid" : 32896,
        "attributes" : {}
    },
    {
        "index" : 3,
        "time" : 1509815973,
        "name" : "StateChanged",
        "attributes" : {}
        "PreviousState" : "None",
        "NewState" : "Lobby"
    },
    {
        "index" : 4,
        "time" : 1509815998,
        "name" : "PlayerChat",
        "refid" : 32896,
        "attributes" : {
            "Message" : "This is a message"
        }
    },
    {
        "index" : 5,
        "time" : 1509816030,
        "name" : "StateChanged",
        "attributes" : {}
        "PreviousState" : "Lobby",
        "NewState" : "Loading"
    },
    {
        "index" : 6,
        "time" : 1509816030,
        "name" : "SessionSetup",
        "attributes" : {}
        "GridSize" : 22,
        "MaxPlayers" : 22,
        "PracticeLength" : 0,
        "QualifyLength" : 15,
        "RaceLength" : 6,
        "Flags" : -1316224232,
        "TrackId" : -52972612,
        "GameMode" : -1958878043
    },
    {
        "index" : 7,
        "time" : 1509816030,
        "name" : "StageChanged",
        "attributes" : {
            "PreviousStage" : "Practice1",
            "NewStage" : "Qualifying1",
            "Length" : 15
        }
    },
    {
        "index" : 8,
        "time" : 1509816046,
        "name" : "StateChanged",
        "attributes" : {
            "PreviousState" : "Loading",
            "NewState" : "Race"
        }
    },
    {
        "index" : 9,
        "time" : 1509816046,
        "name" : "ParticipantCreated",
        "refid" : 32896,
        "participantid" : 0,
        "attributes" : {
            "Name" : "Dealman",
            "IsPlayer" : 1,
            "VehicleId" : 1764851930,
            "LiveryId" : 54
        }
    }]}
}
dynamic jsonObj = JsonConvert.DeserializeObject(messageContent);
foreach(var item in jsonObj)
{
    Trace.WriteLine(item.result);
}
我一直在尝试做这样的事情

{
    "result" : "ok",
    "response" : {
    "first" : 0,
    "count" : 190,
    "now" : 1509822169,
    "events" : [
    {
        "index" : 0,
        "time" : 1509815973,
        "name" : "SessionCreated",
        "attributes" : {}
    },
    {
        "index" : 1,
        "time" : 1509815973,
        "name" : "PlayerJoined",
        "refid" : 32896,
        "attributes" : {}
        "Name" : "Dealman",
        "SteamId" : "76561197986562417"
    },
    {
        "index" : 2,
        "time" : 1509815973,
        "name" : "Authenticated",
        "refid" : 32896,
        "attributes" : {}
    },
    {
        "index" : 3,
        "time" : 1509815973,
        "name" : "StateChanged",
        "attributes" : {}
        "PreviousState" : "None",
        "NewState" : "Lobby"
    },
    {
        "index" : 4,
        "time" : 1509815998,
        "name" : "PlayerChat",
        "refid" : 32896,
        "attributes" : {
            "Message" : "This is a message"
        }
    },
    {
        "index" : 5,
        "time" : 1509816030,
        "name" : "StateChanged",
        "attributes" : {}
        "PreviousState" : "Lobby",
        "NewState" : "Loading"
    },
    {
        "index" : 6,
        "time" : 1509816030,
        "name" : "SessionSetup",
        "attributes" : {}
        "GridSize" : 22,
        "MaxPlayers" : 22,
        "PracticeLength" : 0,
        "QualifyLength" : 15,
        "RaceLength" : 6,
        "Flags" : -1316224232,
        "TrackId" : -52972612,
        "GameMode" : -1958878043
    },
    {
        "index" : 7,
        "time" : 1509816030,
        "name" : "StageChanged",
        "attributes" : {
            "PreviousStage" : "Practice1",
            "NewStage" : "Qualifying1",
            "Length" : 15
        }
    },
    {
        "index" : 8,
        "time" : 1509816046,
        "name" : "StateChanged",
        "attributes" : {
            "PreviousState" : "Loading",
            "NewState" : "Race"
        }
    },
    {
        "index" : 9,
        "time" : 1509816046,
        "name" : "ParticipantCreated",
        "refid" : 32896,
        "participantid" : 0,
        "attributes" : {
            "Name" : "Dealman",
            "IsPlayer" : 1,
            "VehicleId" : 1764851930,
            "LiveryId" : 54
        }
    }]}
}
dynamic jsonObj = JsonConvert.DeserializeObject(messageContent);
foreach(var item in jsonObj)
{
    Trace.WriteLine(item.result);
}
我也尝试过一些其他方法,比如使用列表,但我就是无法让它工作,我一直得到RuntimeBinderException。我已经被困了这么长时间了,现在我开始考虑只使用ReEX,因为这似乎比它的价值更大。

我在这里遗漏了什么和/或误解了什么

    var json = @"...";

    var obj = ToObject(json) as IDictionary<string, object>;
    var resp = obj["response"] as IDictionary<string, object>;
    var events = resp["events"];

    public static object ToObject(string json)
    {
        if (string.IsNullOrEmpty(json))
            return null;
        return ToObject(JToken.Parse(json));
    }

    private static object ToObject(JToken token)
    {
        switch (token.Type)
        {
            case JTokenType.Object:
                return token.Children<JProperty>()
                            .ToDictionary(prop => prop.Name,
                                          prop => ToObject(prop.Value),
                                          StringComparer.OrdinalIgnoreCase);

            case JTokenType.Array:
                return token.Select(ToObject).ToList();

            default:
                return ((JValue)token).Value;
        }
    }
json字符串被转换为字典,其中的项是简单值、列表或嵌套字典。在字典上迭代要比使用反射容易得多


顺便说一句,json中有一个错误-属性之后缺少逗号:{}。另外,将名称和名称同时作为属性不是一个好主意

您遇到的问题是,因为result是一个顶级属性,它不是集合的一部分,所以尝试使用循环访问它没有任何意义。这将按预期打印正常:

using Newtonsoft.Json;
using System;
using System.IO;

namespace SO47114632Core
{
    class Program
    {
        static void Main(string[] args)
        {
            var content = File.ReadAllText("test.json");
            dynamic json = JsonConvert.DeserializeObject(content);
            Console.WriteLine(json.result);
        }
    }
}
我在项目的根文件夹中添加了test.json和您问题中的json,将Copy to Output Directory设置为始终位于文件属性中:


更易于使用的动态版本。

谢谢!至于缺少的逗号,因为它是数组中的最后一个条目,所以有必要吗?此外,返回此数据的HTTP API也嵌入到游戏中。因此,很遗憾,我无法对其进行任何更改。我已经添加了你的代码,我正试图弄清楚它是如何工作的。通过resp[events]循环给了我这个;[first,0][count,302][now,1509826920][events,System.Collections.Generic.List`1[System.Object]]对我来说,它返回了2个错误,我是否缺少一些引用或什么?引发异常:System.Core.dll中的“Microsoft.CSharp.RuntimeBinder.RuntimeBinderException”引发异常:mscorlib中的“Microsoft.CSharp.RuntimeBinder.RuntimeBinderException”。dll@Dealman我试过使用普通的控制台应用程序和.NET核心控制台应用程序,这两种应用程序都能正常工作。事实上,代码是相同的,所以我将编辑我的答案以提供完整的程序。@Dealman Done。如果您仍然有问题,我建议您创建一个新的解决方案并尝试上述方法。如果这样做行得通,你知道这与你当前的项目有关。我肯定它行得通,我只是不太确定RuntimeBinderException的意思——它并没有告诉我太多。您认为这可能是因为我在异步任务中执行此操作?或者在using语句中?string test=json.result;Trace.WriteLinetest;这样做很有效。我猜Trace.WriteLine的工作原理与Console.WriteLine在引擎盖下的工作原理有点不同?哦,非常好!在这里,我想我会用SelectToken以最残忍的方式。。。将做一些更多的测试,但它似乎工作得很好,迄今为止!非常感谢