gpt4 book ai didi

c# - 在 C# 中遍历 JSON 数组

转载 作者:行者123 更新时间:2023-11-30 15:56:17 25 4
gpt4 key购买 nike

我正在尝试弄清楚如何遍历一些 JSON 数据以将其插入到 DataGrid 中,以用作事件日志。然而,尝试解析 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);
}

我也尝试过一些其他方法,例如使用列表,但我就是无法让它工作,而且我一直收到 RuntimeBinderException。我已经坚持了很长时间,现在我开始考虑只使用正则表达式,因为这似乎比它值得的工作更多。

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

最佳答案

   public static ExpandoObject ToExpando(string json)
{
if (string.IsNullOrEmpty(json))
return null;
return (ExpandoObject)ToExpandoObject(JToken.Parse(json));
}


private static object ToExpandoObject(JToken token)
{

switch (token.Type)
{
case JTokenType.Object:
var expando = new ExpandoObject();
var expandoDic = (IDictionary<string, object>)expando;
foreach(var prop in token.Children<JProperty>())
expandoDic.Add(prop.Name, ToExpandoObject(prop.Value));
return expando;
case JTokenType.Array:
return token.Select(ToExpandoObject).ToList();

default:
return ((JValue)token).Value;
}
}

var ebj = ToExpando(json);
var name = (ebj as dynamic).response.events[1].name;

使用动态的更好(更易于使用)的版本。

关于c# - 在 C# 中遍历 JSON 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47114632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com