2014-01-13 3 views
7

リソースファイル(.resx)からJSONオブジェクトを作成します。私は、次のようなResouceSetにそれを変換:.NET C#でResourceSetをJSONに変換する

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

私は今の形{Key:<key>, Value:<value>}内のオブジェクトのセットを持っていますが、代わりにフォームまたはハッシュマップ{Key:Value, ...}にJSONに変換したいと思います。 ResourceSet以来

+0

は、あなたはそれがシリアル化されますが、 'resourceSet'のJSONをしたいか、あなたはそれをさらに制御したいんです。だから、Karhgathのソリューションに構築するために私はちょうど辞書を通じてループ? –

+0

あなたのリソースセットはテキストのみを含むことが保証されていますか、それとも画像/アイコンも含まれていますか? – vcsjones

+0

リソースにはテキストのみが含まれています。 –

答えて

17

が古いコレクションクラス(ハッシュテーブル)であるとDictionaryEntryを使用して、あなたはDictionary<string, string>へのResourceSetを変換し、それをシリアル化するJson.Netを使用する必要があります。

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

var jsonString = JsonConvert.SerializeObject(resourceSet); 
0

私はKarhgathのソリューションを言っていますが、私はdidnのすでにキー/値のペアを持つリストがあるので、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 + " }"; 
} 
関連する問題