10

I'm using Jint to execute JavaScript in a Xamarin app. Jint is converting an associative array into an ExpandoObject. How do I use this object? Ideally, I'd like to get a dictionary of the data out of it.

JavaScript returns:

return {blah:abc, bleh:xyz};

Debugger of Object that Jint returns looks like:

enter image description here

Chris Williams
  • 11,647
  • 15
  • 60
  • 97
  • 2
    @bzlm: Not a dupe. This is specific how-to question about creating a dictionary from `ExpandoObject`. – recursive Sep 16 '15 at 20:54
  • 2
    The only way to do it I've found is: `((IDictionary)result).ToDictionary(nvp => nvp.Key, nvp => nvp.Value)` – toddmo Mar 25 '17 at 00:32

2 Answers2

33

It already IS a dictionary. Just implicitly cast it:

IDictionary<string, object> dictionary_object = expando_object;

And then use it like one. BTW: this is also the reason why recursive's solution works.

Community
  • 1
  • 1
Zotta
  • 2,513
  • 1
  • 21
  • 27
  • 1
    This doesn't change the json behavior. It still serializes as `[{"Key":"Property1Name", "Value":"Property1Value"}, {"Key":"Property2Name", "Value":"Property2Value"}]` – toddmo Mar 25 '17 at 00:29
18

Just pass it to the constructor.

var dictionary = new Dictionary<string, object>(result);
recursive
  • 83,943
  • 34
  • 151
  • 241
  • 1
    If `result` is `object`, which on `expando` I believe it is, then this won't compile. It will find the constructor that takes an `int` instead. – toddmo Mar 25 '17 at 00:30
  • Everything is an object. But result is dynamically typed and the concrete type implements IDictionary. Try it and you'll see. – recursive Mar 25 '17 at 02:39
  • 1
    I did. It won't compile like that. I have a list of expando objects and `Json(results.Data.Select(o => new Dictionary(o))` won't compile. I get error: "CS1503 Argument 1: cannot convert from 'object' to 'int'". Hovering over `o` tells me that parameter `o` is `object`. So, `results.Data.Select(o => ((IDictionary)o).ToDictionary(nvp => nvp.Key, nvp => nvp.Value))` is the only way I could get it to work. – toddmo Mar 25 '17 at 18:23
  • 2
    The dictionary constructor takes an `IDictionary`, which `ExpandoObject` is. However if the static declaration of your variable is `object`, the compiler can't verify it. `ExpandoObject` instances are usually declared dynamic. That would work. In your example, you cast `o` to `(IDictionary)`. – recursive Mar 26 '17 at 00:40