簡體   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