简体   繁体   English

将C#List转换为JSON特定格式

[英]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: 在我的Action中,我创建了一个包含2个属性的列表:

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: 现在我想将此列表转换为JSON格式,如下所示:

[
{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 ... 设备的价值是=小时,geekbench =销售...

How could I do this in C#? 我怎么能在C#中做到这一点?

With Json.Net and Linq it's easy: 使用Json.Net和Linq很容易:

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. 您使用您想要的字段和名称投影匿名类型,让Newtonsoft.Json完成剩下的工作。

since you are using mvc why not use return Json() it will convert the object to json string you can use it like 因为你正在使用mvc为什么不使用return Json()它会将object转换为json字符串,你可以使用它

  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 您可以使用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. 导入命名空间System.Web.Script.Serialization ,它是Microsoft的Inbuilt类,用于处理JSON。 You will need to refer additional assembly named System.Web.Extensions using 'Add References'. 您需要使用“添加引用”引用名为System.Web.Extensions的其他程序集。

using System.Web.Script.Serialization;

Declare List and Convert into customized JSON Format 声明列表并转换为自定义的JSON格式

        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 您将在's'变量中获得以下输出

[{"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. 注意: 如果要获得性能优化,那么最好使用Newtonsoft JSON Library而不是Microsoft的Default JSON Library。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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