使用 JSON.NET 将字典转换为 JSON

Converting a Dictionary to JSON with JSON.NET

我在将字典转换为 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 Whosebug post
    //

    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

我已经尝试了很多其他的 Whosebug 答案。我不知道该尝试什么了。

到目前为止谢谢!

为了获得具有电影和利润属性的 JSON,您需要创建一个 DTO(数据传输对象),例如

public class MovieProfit
{
    public string Title { get; set; }
    public double Profit { get; set; }
}

然后使用 Linq

将您的字典转换为该 DTO 的列表
List<MovieProfit> plist = profitList.Select(keyValuePair => new MovieProfit() { Title = keyValuePair.Key.Title, Profit = keyValuePair.Value }).ToList();

您现在将获得所需的 JSON 连载。

关于引号,这是因为您将对象序列化为 JSON 字符串并将该字符串传回 ViewModel。如果将对象或对象列表传回,则不会遇到此问题。

首先,您应该删除 TypeNameHandling = TypeNameHandling.All 设置。这就是您的 JSON 包含 $type 属性.

的原因

其次,您应该使用 @Html.Raw(Model.ProfitListJson) 来呈现没有 &quot 的 JSON 字符串。

您的视图中有这样的内容:

var jsonObj = @Html.Raw(Model.ProfitListJson);
var chart = AmCharts.makeChart("chart_6", {
    //...
    "dataProvider": jsonObj,
    //...
});

你的控制器中有这样的东西:

string json = JsonConvert.SerializeObject(plist, 
  Formatting.Indented, 
  new JsonSerializerSettings
{
    TypeNameAssemblyFormat = FormatterAssemblyStyle.Simple // I don't think this is needed, but leaving it in in case you had a reason for it
});

答案应该是这样的,使用 jobject (newtonsoft.json.linq)

JObject o = new JObject
        (
            new JProperty("DataProvider",
                new JArray(
                    from m in List
                    select new JObject(
                        new JProperty("title",m.Key),
                        new JProperty("profit",m.Value))))
        );

就是这样,您可以使用 o.tostring()

显示

输出类似于

{
  "DataProvider": [
    {
      "title": "movie1",
      "profit": 2121.0
    },
    {
      "title": "movie2",
      "profit": 47877.0
    }
  ]
}