繁体   English   中英

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

[英]Converting a Dictionary to JSON with JSON.NET

我在将dictonairy转换为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",

调试时我在控制器中得到的当前结果 在此输入图像描述

铬的结果 在此输入图像描述

我已经尝试了很多其他Stackoverflow的答案。 我不知道该怎么办了。

谢谢到目前为止!

在此输入图像描述

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

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)来渲染你的JSON字符串而不是&quot

您的视图中有类似的内容:

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 } ] } 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM