简体   繁体   English

C#和RestSharp的JSON解析问题

[英]JSON Parsing issue with C# and RestSharp

I am parsing the following JSON: 我正在解析以下JSON:

{
result: [
  {
    EventType: {
    EventTypeDesc: "horse-racing",
    events: {
      Local: {
        Events: {
          530857: {
            Venue: "Northam",
            StateCode: "WA",
            CountryCode: "AUS"
            },
          530858: {
            Venue: "Caulfield",
            StateCode: "VIC",
            CountryCode: "AUS"
            }
          }
        }
      }
    }
  }
  ]
}

I can access the element through following code: 我可以通过以下代码访问元素:

responseDeserializeObject.result[0].EventType.events.Local.Events["530857"].Venue responseDeserializeObject.result [0] .EventType.events.Local.Events [“ 530857”]。地点

However, the following C# code doesn't work: 但是,以下C#代码不起作用:

dynamic responseDeserializeObject = HttpGetResponse(endPoint);
foreach (var event in responseDeserializeObject.result[0].EventType.events.Local.Events)
{
  Console.WriteLine(event.Venue);
  Console.WriteLine(event.StateCode);
  Console.WriteLine(event.CountryCode);
}

Any help will be highly appreciated. 任何帮助将不胜感激。

I think your Events is a dictionary, so you need to get KeyValuePair in the foreach loop and access it's Value property. 我认为您的Events是一本字典,因此您需要在foreach循环中获取KeyValuePair并访问它的Value属性。 And also change the scoped variable name event , it will not compile, event is a reserved word. 并且还更改了作用域变量名称event ,它不会编译, event是保留字。

dynamic responseDeserializeObject = HttpGetResponse(endPoint);
foreach (var ev in responseDeserializeObject.result[0].EventType.events.Local.Events)
{
  var value = ev.Value;

  Console.WriteLine(value.Venue);
  Console.WriteLine(value.StateCode);
  Console.WriteLine(value.CountryCode);
}

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

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