gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 20:56:28 25 4
gpt4 key购买 nike

我有以下存储所有数据的 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 以显示在谷歌图表中。目前,我有 View 在 Coin Controller 中调用一个名为 Data 的方法来接收数据,但我无法使其正常工作。

硬币 Controller :

    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);
}

用于处理和显示数据的 View 中的 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 ,它是文件的内容。您需要将其反序列化为 Coin 对象列表。您的客户端代码需要一组对象,每个对象都有一个 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);
}

关于javascript - 如何从 MVC 中的 JSON 对象中获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47610435/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com