2014-01-13 45 views
7

我想從資源文件(.resx)創建JSON對象。我把它轉換成ResouceSet這樣:.NET C#將ResourceSet轉換爲JSON

ResourceSet resourceSet = MyResourceClass.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true); 

我現在有一組的形式{Key:<key>, Value:<value>}對象而是會想將它轉化成JSON形式或哈希地圖{Key:Value, ...}

+0

你只想但是'resourceSet'它被序列化的JSON或你想有超過更多的控制權:所以建立在Karhgath的解決方案,我只是通過字典環? –

+0

您的資源集保證只包含文本,還是包含圖片/圖標? – vcsjones

+0

資源只包含文本。 –

回答

17

由於ResourceSet是一個古老的集合類(哈希表),並使用DictionaryEntry,您需要將的ResourceSet轉換爲Dictionary<string, string>和使用Json.Net連載之:

resourceSet.Cast<DictionaryEntry>() 
      .ToDictionary(x => x.Key.ToString(), 
         x => x.Value.ToString()); 

var jsonString = JsonConvert.SerializeObject(resourceSet); 
0

我喜歡Karhgath的解決方案,但我沒有我不想使用Json.Net,因爲我已經有了一個包含鍵/值對的列表。

public static string ToJson(ResourceManager rm) { 
    Dictionary<string, string> pair = new Dictionary<string, string>(); 
    ResourceSet resourceSet = rm.GetResourceSet(CultureInfo.CurrentUICulture, true, true); 

    resourceSet.Cast<DictionaryEntry>().ToDictionary(x => x.Key.ToString(), x => x.Value.ToString()); 

    string json = ""; 

    foreach (DictionaryEntry item in resourceSet) { 
     if (json != "") { json += ", "; } 
     json += "\"" + item.Key + "\": \"" + item.Value + "\""; 
    } 

    return "{ " + json + " }"; 
}