2016-11-05 71 views
-1

此問題與Json數據格式有關。我有一個帶有Key值對的字典。 ConfigA 1200 ConfigB 1500 ConfigC 800 ConfigD 2 .I需要將所有字典值轉換爲1種JSON格式 [{ 「ConfigA」: 「1200」, 「ConfigB」: 「1500」, 「ConfigC」:」 800「,」ConfigD「:」2「}] 任何人都可以幫助我如何做到這一點?C#Dictionary to Json格式

+0

使用newtonsoft。 http://www.newtonsoft.com/json/help/html/DeserializeDictionary.htm –

+0

可能的重複[如何將字典轉換爲C#中的JSON字符串?](http://stackoverflow.com/questions/5597349 /怎麼辦,我變頻-A-字典至A-JSON字符串,在-C) –

回答

0

添加System.Web.Extensions.dll和嘗試下面的代碼,

using System; 
using System.Collections.Generic; 
using System.Web.Script.Serialization; 

public class Program 
{ 
    public static void Main() 
    { 
     var dictionary = new Dictionary<string, int> { 
      {"ConfigA", 1200}, 
      {"ConfigB", 1500}, 
      {"ConfigC", 800}, 
      {"ConfigD", 2} 
     }; 

     var serializer = new JavaScriptSerializer(); 
     Console.WriteLine(serializer.Serialize(dictionary)); 
    } 
} 
0

可能相同this question

只是出於興趣,你知道你正在創建包含一個數組有4個參數的對象?假設JavaScript將成爲此結構的目標,那麼您將引用data [0] .config *。您可能想要在開始和結束時忽略方括號以使接收方JS代碼更易於理解。下面之前和之後的示例。

// using array 
var data = jQuery.parseJSON('[{"ConfigA":"1200","ConfigB":"1500","ConfigC":"800","ConfigD":"2"}]') 

var A = data[0].configA 
alert('Value of A=' + A) // Will show 1200 

var B = data[0].configB 
alert('Value of B=' + B) // Will show 1500 

// without array 
var dataV2 = jQuery.parseJSON('{"ConfigA":"1200","ConfigB":"1500","ConfigC":"800","ConfigD":"2"}') 

var A2 = data.configA 
alert('Value of A2=' + A2) // Will show 1200 

var B2 = data.configB 
alert('Value of B2=' + B2) // Will show 1500