如何从MVC中的JSON对象中获取数据

我有以下用于存储所有数据的JSON对象。如何从MVC中的JSON对象中获取数据

[{"id":1,"CoinValue":"0.01","Count":82,"CoinWeight":76}, 

{"id":2,"CoinValue":"0.02","Count":86,"CoinWeight":18},

{"id":3,"CoinValue":"0.05","Count":29,"CoinWeight":42},

{"id":4,"CoinValue":"0.1","Count":35,"CoinWeight":90},

{"id":5,"CoinValue":"0.2","Count":23,"CoinWeight":3},

{"id":30,"CoinValue":"0.5","Count":41,"CoinWeight":36}]

我想获取每个记录的CoinValue和Count以便在谷歌图表中显示。目前,我有一个视图调用Coin控制器中的一个名为Data的方法来接收数据,但是我无法实现这个功能。

CoinController:

public ActionResult Data() 

{

//Read Json object

var fileContents = System.IO.File.ReadAllText(@"H:\EasyAsPiMVC\EasyAsPiMVC\App_Data\MOCK_DATA.json");

//not sure how to properly pass this data to the view

return Json(fileContents);

}

的Javascript鉴于处理和显示数据

<script type="text/javascript"> 

$(document).ready(function() {

$.ajax({

type: 'POST',

dataType: "Json",

contentType: "application/json",

url: '@Url.Action("Data", "Coin")',

success: function (result) {

google.charts.load('current', {

'packages': ['corechart']

});

google.charts.setOnLoadCallback(function() {

drawChart(result);

});

}

});

function drawChart(result) {

var data = new google.visualization.DataTable();

data.addColumn("string", "CoinValue"); //might have to be changed

data.addColumn("number", "Count");

var dataArray = [];

$.each(result, function (i, obj) {

dataArray.push([obj.CoinValue, obj.Count]);

});

data.addRows(dataArray);

var piechart_options = {

title: 'Coin Tracker Piechart',

width: 400,

height: 300

};

var piechart = new google.visualization.PieChart(document.getElementById('piechart_div'));

piechart.draw(data, piechart_options);

var barchart_options = {

title: 'Coin Tracker barchart',

width: 400,

height: 300,

legend: 'none'

};

var barchart = new google.visualization.BarChart(document.getElementById('barchart_div'));

barchart.draw(data, barchart_options);

}

});

</script>

我是一个编程小白和一直没能到现在过了一天算出来的。我做了大量的研究,但我似乎无法得到这个工作。

回答:

ReadAllText方法为您提供string,这是该文件的内容。您需要将其反序列化为​​对象列表。您的客户端代码需要一个对象数组,每个对象都有一个CoinValueCount属性。所以你需要返回这个json数组。

这里是你将如何与JSON.NET

[HttpPost] 

public ActionResult Data()

{

var path = "Path to your JSON file goes here";

var fileContents = System.IO.File.ReadAllText(path);

var list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Coin>>(fileContents);

return Json(list);

}

以上是 如何从MVC中的JSON对象中获取数据 的全部内容, 来源链接: utcz.com/qa/257462.html

回到顶部