.NET C#将ResourceSet转换为JSON

时间:2014-01-13 19:26:28

标签: c# json

我想从资源文件(.resx)创建一个JSON对象。我将其转换为ResouceSet

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

我现在有{Key:<key>, Value:<value>}形式的一组对象,而是希望将其转换为表单中的JSON或哈希映射{Key:Value, ...}

2 个答案:

答案 0 :(得分:19)

由于ResourceSet是旧的集合类(HashTable)并使用DictionaryEntry,因此您需要将resourceSet转换为Dictionary<string, string>并使用Json.Net对其进行序列化:

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

var jsonString = JsonConvert.SerializeObject(resourceSet);

答案 1 :(得分:0)

我喜欢Karhgath的解决方案,但我不想使用Json.Net,因为我已经有一个包含键/值对的列表。因此,为了建立Karhgath的解决方案,我只是在字典中循环:

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 + " }";
}