【发布时间】:2015-05-31 23:54:05
【问题描述】:
我在将字典转换为 JSON.NET 时遇到问题。我确定我遗漏了一些要点。此外,我在使用 JSON 方面的经验很少,而且我主要是从 php 而不是从 c# 中完成的。
它添加了我缺少的 &qout
//GENERAL NOTE: IT's a school project (so not much focus on security)
//C#
public ActionResult GetChartData(string startDate, string endDate)
{
Dictionary<Movie, double> profitList = //Gets data from repository
//in the json list i want the movie names not the objects so I make another dictonairy to convert to json
Dictionary<string, double> plist = profitList.ToDictionary(keyValuePair => keyValuePair.Key.Title, keyValuePair => keyValuePair.Value);
//Code from other stackoverflow post
//http://stackoverflow.com/questions/3739094/serializing-deserializing-dictionary-of-objects-with-json-net
string json = JsonConvert.SerializeObject(plist, Formatting.Indented, new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All,
TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple
});
//ViewModel i Use
FinancialViewModel viewModel = new FinancialViewModel
{
ProfitList = profitList,
ProfitListJson = json,
Start = start,
End = end
};
return PartialView("_FinancialPartialView", viewModel);
}
//JS
<script>
var chart = AmCharts.makeChart("chart_6", {
"type": "pie",
"theme": "light",
"fontFamily": "Open Sans",
"color": "#888",
"dataProvider": @Model.ProfitListJson,
"valueField": "movie", //the name from the movie
"titleField": "profit", //the profit from the movie
"exportConfig": {
menuItems: [
{
icon: Metronic.getGlobalPluginsPath() + "amcharts/amcharts/images/export.png",
format: "png"
}
]
}
});
</script>
这是我想要得到的结果
"dataProvider": [{
"movie": "Title of movie 1",
"profit": Profit of movie 1
}, {
"movie": Title 2c",
"profit": Profit 2
}],
"valueField": "movie",
"titleField": "profit",
调试时我在控制器中得到的当前结果
chrome 中的结果
我尝试了很多其他 Stackoverflow 答案。我不知道该尝试什么了。
到目前为止谢谢!
【问题讨论】:
-
您是否要对
plist进行双重序列化——对其进行序列化,然后将字符串嵌入到要重新序列化的类中?还有,为什么要同时返回plist的序列化json和ProfitList字典呢? -
@dbc 它们都被返回,因为我在部分视图中使用数据表的利润列表。我必须检查您评论的另一部分。
-
Json.NET 不会将具有复杂类的字典序列化为 keys。见here。这里有一些解决方法:How can I serialize/deserialize a dictionary with custom keys using Json.Net?.
-
@dbc 他在序列化之前将其转换为 Dictionary
。 -
不,视图模型不会自动序列化,因此它们的属性可以是任何类型。