vbuser2004
vbuser2004

Reputation: 1032

How to structure c# poco so that it works with time series json data in Highcharts?

I am working on creating a time series chart using Highcharts.js like the one in this example:

http://www.highcharts.com/demo/spline-irregular-time

This chart has date and data in a series that I am accessing via an ajax call to a c# api that then returns json. I have been successful in doing this with bar charts and basic numeric data. However, I can't seem to generate the Date/Time data like in this example.

My question is - how do I structure my c# poco so that I can in turn, send back valid json to the chart in the correct date format (like this sample)? My poco is filled with data from a SQL Server database.

The json data in the sample is in this format (see below). When I attempt to create a poco of this data using http://json2csharp.com/ I get an error that the json is not valid. I realize I could probably manually create a string to generate this date data, but I wanted to avoid that if possible.

Thank you for your help or suggestions.

json sample data:

series: [{ name: 'Winter 2007-2008', // Define the data points. All series have a dummy year // of 1970/71 in order to be compared on the same x axis. Note // that in JavaScript, months start at 0 for January, 1 for February etc. data: [ [Date.UTC(1970, 9, 27), 0 ], [Date.UTC(1970, 10, 10), 0.6 ], [Date.UTC(1970, 10, 18), 0.7 ], [Date.UTC(1970, 11, 2), 0.8 ], [Date.UTC(1970, 11, 9), 0.6 ] .... ] }...

Upvotes: 0

Views: 808

Answers (2)

vbuser2004
vbuser2004

Reputation: 1032

I determined the best object to create looked like this:

public class SeriesOfData
{
    public string name { get; set; }
    public List<double[]> data { get; set; }
}

This enabled me to convert to json and achieve an array of points in a series, and each series would be a set of 2 double values (datetime in javascript milliseconds since 1970, and then the associated value/reading). As these are in an array they are not 'named' when rendered as json, so the resulting json text is in the propoer form. It was also much easier to read the code when assigning these values to the array, and I can add additional series of data as needed just by instantiating a new SeriesOfData object. Not sure if this is the best way, but it works for me. Appreciate any suggestions on improvements.

Upvotes: 0

Paweł Fus
Paweł Fus

Reputation: 45079

Because this is not proper JSON, use jsonlint or something similar before. For example proper JSON:

[{ "name": "Winter 2007-2008", "data": [ [25833600000, 0 ], [27043200000, 0.6 ], [27734400000, 0.7 ], [28944000000, 0.8 ], [29548800000, 0.6 ]  ] }]

As you can see, changed are:

  • name -> "name"
  • 'Winter 2007-2008' -> "Winter 2007-2008"
  • all Date.UTC() functions to proper numbers

These numbers are values returned by Date.UTC(), so are number of milliseconds since 1970.01.01 00:00:00:000 in UTC time.

Upvotes: 0

Related Questions