Search code examples
jsonhighchartsdotnethighcharts

DotNet.Highcharts and proper JSON


I have an inconsistent issue with the JSON sent to highcharts. Highcharts does not always reject the JSON, but when it does, updating the JSON by hand to a proper format consistently fixes it:

Exmaple DotNet.Hightcharts output:

series: [{ data: [284, 49, 100, 19], name: 'some name' }, { data: [230, 250, 219, 878], name: 'some name 2' }]

when fixed to included quotes it works:

 "series": [{ "data": [284, 49, 100, 19], "name": "some name" }, { "data": [230, 250, 219, 878], "name": "some name 2" }]

Is there a way to get DotNet.Hightcharts to output this format?


Solution

  • Looking at the DotNet.Highcharts source code, it seems it uses its own JsonSerializer which does not quote property names, and there's no option to change this behavior nor swap out the serializer for another one altogether. They have made it straight forward to change the formatting in code though, so it looks like changing the following lines in: DotNet.Highcharts/JsonSerializer.cs should do what you need:

    const string JSON_PROPERTY_WITH_VALUE_FORMAT = "{0}: {1}";
    const string JSON_STRING_FORMAT = "'{0}'";
    

    to become:

    const string JSON_PROPERTY_WITH_VALUE_FORMAT = "{\"0\"}: {1}";
    const string JSON_STRING_FORMAT = "\"{0}\"";
    

    So I'd say you options are:

    1. Compile your own version of DotNet.Highcharts using the source code with the above alterations.

    2. Convince the project developers to include such changes in the next release.

    3. Use an alternative library such as Highcharts.Net which does quote names by default.

    4. Use no library at all and just render your data into a literal placed inside the hand-coded Highcharts javascript, using a stand alone Json formatter like Newtonsoft.Json.

    Before any of the above though, it does sound a bit odd that this problem only emerges as more data is added. It's not just a case of apostrophes in your data breaking the format is it? They don't appear to be being escaped in the formatter.