Aby
Aby

Reputation: 11

JSON Parsing issue with C# and RestSharp

I am parsing the following 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

However, the following C# code doesn't work:

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.

Upvotes: 0

Views: 147

Answers (1)

Suren Srapyan
Suren Srapyan

Reputation: 68635

I think your Events is a dictionary, so you need to get KeyValuePair in the foreach loop and access it's Value property. And also change the scoped variable name event, it will not compile, event is a reserved word.

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);
}

Upvotes: 2

Related Questions