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

时间:2015-03-27 15:25:49

标签: c# json 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",

我在调试时进入控制器的当前结果 enter image description here

chrome的结果 enter image description here

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

到目前为止感谢!

enter image description here

3 个答案:

答案 0 :(得分:2)

为了获得具有电影和利润属性的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。如果您将对象或对象列表传回,则不会遇到此问题。

答案 1 :(得分:1)

首先,您应该删除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
});

答案 2 :(得分:0)

答案应该是这样的使用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()

来显示

输出类似于

&#13;
&#13;
{
  "DataProvider": [
    {
      "title": "movie1",
      "profit": 2121.0
    },
    {
      "title": "movie2",
      "profit": 47877.0
    }
  ]
}
&#13;
&#13;
&#13;