Search code examples
c#jsonasp.net-mvchighchartsjavascriptserializer

JSON Result for Highcharts Data Object in C#


I am trying to take a List of a custom class and convert it to JSON in MVC/C#. I have used both json.encode and javascriptserializer to no avail. The json data is shown with &.quot; instead of the single or double quotes. Here's what I believe is the relevant code. This data is going to be used in a highcharts application.

My Models

public class DataPoint
{
    public double? data { get; set; } //CTDI value
    public DateTime? DateOfScan { get; set; }
    public string Name { get; set; }
    public string Nmmber{ get; set; }
    public int PersonDatabaseID { get; set; }
    public string EquipmentName{ get; set; }
}

public class PlotData : List<DataPoint>
{
}

public class PlotListModel : List<PlotData>
{
}

My View

foreach (PlotData pd in (PlotListModel) ViewBag.MyData)
{
    JavaScriptSerializer js = new JavaScriptSerializer();
    var jsData1 = js.Serialize(pd);

    //Or use JSON.Encode
    var jsData2 = Json.Encode(pd);

    string divID = "container" + i;
    <div id='@divID'>
        <script type='text/javascript'>
            $(function () {
                var chart = new Highcharts.Chart({
                    chart: {
                        renderTo: '@divID',
                        type: 'colummn'
                    },
                    title: {text: '@divID'},
                    tooltip: {
                        formatter: function () {
                            return 'Extra data: <b>' + this.point.Scanner + '</b>';
                        }
                    },

                    series: [{
                        name: 'Foo',
                        data: ['@jsData1']
                    }]
                });
            });
        </script>
    </div>

    i += 1;
}

When I look at the page source I see the data fields and values surrounded by the encoded quote value - &quot;

Solution

  • You should create a webapi controller and it should contain a method that looks something like this. I am assuming you're using Web Api 2.0 with this example.

    [Route("api/plotlist")]
    [HttpGet]
    public PlotListModel GetPlotList() {
        //Here's where you would instantiate and populate your model
        PlotListModel plotList; 
    
        /*
         * Once your model is instantiated and populated then you can
         * just return it and the serialization will be done for you
         */
    
        return plotList;
    }
    

    Once you have that you can then call that method from your client code using ajax. A simple client function might look something like this if you use jQuery.

    function retreivePlotList() {
        $.getJSON("http://<base url>/api/plotlist", function(data) { 
            //do something with data 
        });
    }