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#?
-
Something like this would work ? new JavaScriptSerializer().Deserialize<HourlyGraph>(yourList);Joab Santos– Joab Santos2017年03月14日 14:11:24 +00:00Commented Mar 14, 2017 at 14:11
-
Did you have a look at the Newtonsoft.JSON library? You will find it on nugetTom Doodler– Tom Doodler2017年03月14日 14:11:36 +00:00Commented Mar 14, 2017 at 14:11
-
@TomDoodler yes but what confuses me here is how do I set the first string in json to be named like "device" and "geekbench" ?User987– User9872017年03月14日 14:12:43 +00:00Commented Mar 14, 2017 at 14:12
-
@joab what about "device" and "geekbench" values, how do I place them in JSON response ?User987– User9872017年03月14日 14:13:28 +00:00Commented Mar 14, 2017 at 14:13
-
Somethin like this would work ? [JsonProperty(PropertyName = "device")] public int Hour {get;set;}Joab Santos– Joab Santos2017年03月14日 14:15:16 +00:00Commented Mar 14, 2017 at 14:15
3 Answers 3
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.
9 Comments
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 }));
}
1 Comment
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.