Search code examples
c#jsondatetimecompareweather-api

Parse JSON and find element with closest matching date


I have a JSON string containing some data.

I do not have types declared to match and am using dynamics, as there are many, many instances where API calls are made and JSON with totally different structures are returned.

What I am trying to do is loop through the array of entries in the first element of days - and get the entry where it's dateTime closely matches the current date time.

The error I am having is :

Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot implicitly convert type Newtonsoft.Json.Linq.JArray' tostring'. An explicit conversion exists (are you missing a cast?)

I believe there's some added complexity with the need to use dynamics, and navigating through the reasonably complex data structure.

Here is what I have tried.

dynamic windData = JsonConvert.DeserializeObject(resultWindAPI); //resultWindAPI is the JSON presented below. 

string windEntries = windData.forecasts.wind.days[0].entries;
dynamic windEntryData = JsonConvert.DeserializeObject(windEntries);

//find closest wind time to get most recent data
int min = int.MaxValue;
DateTime now = new DateTime();
dynamic currentWindEntry = windEntryData[0];

foreach(dynamic entry in windEntryData)
{
    DateTime thisDateTime = entry.dateTime;

    if (Math.Abs(thisDateTime.Ticks - now.Ticks) < min)
    {
        min = (int)thisDateTime.Ticks - (int)now.Ticks;
        currentWindEntry = entry;
    }
}

//Do something with the currentWindEntry 

Here is an example of the JSON I am trying to parse.


Solution

  • According to the error message

    string windEntries = windData.forecasts.wind.days[0].entries;
    

    is the problem.

    You already have access to the entries via the dynamic variable before so just assign it.

    dynamic windEntryData = windData.forecasts.wind.days[0].entries;