简体   繁体   中英

Converting C# List into JSON specific format

I have a graph in my view which looks like this:

  var hourlyGraph = Morris.Bar({
            element: 'graph_bar',
            data: [
               @foreach (var item in ViewBag.HourlyGraph)
               {
                @:{device: '@item.Hour.ToString("D2"):00', geekbench:@item.Sales },
               }
            ],
            xkey: 'device',
            ykeys: ['geekbench'],
            labels: ['Sold'],
            barRatio: 0.4,
            barColors: ['#0A4D70', '#34495E', '#ACADAC', '#3498DB'],
            xLabelAngle: 35,
            hideHover: 'auto',
            resize: true
      });

This is a morris chart. Note how the data is set up here:

[
@foreach (var item in ViewBag.HourlyGraph)
{
@:{device: '@item.Hour.ToString("D2"):00', geekbench:@item.Sales },
}
]

And now I need to fill the chart with new data. In my Action I have created a list which contains 2 properties:

public int Hour {get;set;}
public int Sales {get;set;}

And they are stored into a list typed of:

var HourlyGraph = new List<HourlyGraph>();

Now I'd like to convert this list into a JSON format which would look something like this:

[
{device: '0', geekbench:5 },
{device: '1', geekbench:13 },
{device: '2', geekbench:25 },
{device: '3', geekbench:14 },
{device: '4', geekbench:16 },
]

Where value for device would be = hour, and geekbench = sales ...

How could I do this in C#?

With Json.Net and Linq it's easy:

string myJson = 
   JsonConvert.SerializeObject(mylist.Select(item=>
                                  new {device=item.Hour, geekbench=item.Sales}));

You project an anonymous type with the fields and names that you'd like, and let Newtonsoft.Json do the rest.

since you are using mvc why not use return Json() it will convert the object to json string you can use it like

  public ActionResult Myaction()
    { 
        var HourlyGraph = new List<HourlyGraph>();


        return Json(HourlyGraph.Select(x => new {Hour=x.Hour,Sales=x.Sales }));
    }

You can achieve the desired output by using LINQ Anonymous Type

As per example following is class

public class HourlyGraph
{
    public int Hour { get; set; }
    public int Sales { get; set; }
}

Import Namespace System.Web.Script.Serialization which is a Microsoft's Inbuilt Class for dealing with JSON. You will need to refer additional assembly named System.Web.Extensions using 'Add References'.

using System.Web.Script.Serialization;

Declare List and Convert into customized JSON Format

        var listHourlyGraph = new List<HourlyGraph>();

        //Adding some Sample Values
        listHourlyGraph.Add(new HourlyGraph() { Hour = 0, Sales = 5 });
        listHourlyGraph.Add(new HourlyGraph() { Hour = 1, Sales = 10 });

        //Declaring JavaScriptSerialzer Object
        var serialzer = new JavaScriptSerializer();

        //Using Serialize Method which returns back a JSON String
        //We are using LINQ SELECT Method to create a new anonymous return type which contains our custom return types
        string s = serialzer.Serialize(listHourlyGraph.Select(x => new { device = x.Hour, geekbench = x.Sales } ));

You will get the following output in 's' variable

[{"device":0,"geekbench":5},{"device":1,"geekbench":10}]

Note: If you want to get performance optimizations then you are better using Newtonsoft JSON Library instead of Microsoft's Default JSON Library.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM