2011-12-29 19 views
2

私は辞書変換辞書

Dictionary<string, object> dict; 

を持っていると私は辞書

string foo = dict["foo"].ToString(); 

を入力してから値を取得するには、シリアル化されたJSONの結果です。

私はその他場合、オブジェクトに変換する方法を知っていただきたいと思いますので、私のようなものを入力することができますどのような
serializer.Deserialize<Dictionary<string, object>>(HttpContext.Current.Request["JSON"]); 

:あなたがわからない場合

string foo = dict.foo; 

おかげ

答えて

2

を辞書の正確なメンバーdynamicを使用すると、以下に示すようなかなりの構文を得ることができます。しかし、あなたが辞書のメンバーとタイプを知っていれば、then you could create your own classと自分で変換を行います。自動的にそれを行うためのフレームワークが存在するかもしれません。

using System; 
using System.Collections.Generic; 
using System.Text; 
using System.Dynamic; 

namespace DynamicTest 
{ 
    public class DynamicDictionary : DynamicObject 
    { 
     Dictionary<string, object> dict; 

     public DynamicDictionary(Dictionary<string, object> dict) 
     { 
      this.dict = dict; 
     } 

     public override bool TrySetMember(SetMemberBinder binder, object value) 
     { 
      dict[binder.Name] = value; 
      return true; 
     } 

     public override bool TryGetMember(GetMemberBinder binder, out object result) 
     { 
      return dict.TryGetValue(binder.Name, out result); 
     } 
    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      dynamic foo = new DynamicDictionary(new Dictionary<string, object> { { "test1", 1 } }); 

      foo.test2 = 2; 

      Console.WriteLine(foo.test1); // Prints 1 
      Console.WriteLine(foo.test2); // Prints 2 
     } 
    } 
} 
+1

このフレームワークは実際に存在し、[Automapper](http://automapper.org/)と呼ばれています。 –

関連する問題