3

I have a dictionary

Dictionary<string, object> dict;

And i get values from it by typing

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

The dictionary is a serialized JSON result.

serializer.Deserialize<Dictionary<string, object>>(HttpContext.Current.Request["JSON"]);

What i would like to know if thers a way to convert it to an object, so i can type something like:

string foo = dict.foo;

Thanks

Johan
  • 35,120
  • 54
  • 178
  • 293

1 Answers1

2

If you don't know the exact members of the dictionary you can use dynamic to get a pretty syntax as shown below. However, if you know the members of the dictionary and the types, then you could create your own class and do the conversion yourself. There might exists a framework to do that automatically.

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
        }
    }
}
Community
  • 1
  • 1
Lasse Espeholt
  • 17,622
  • 5
  • 63
  • 99