4

I had the cunning idea of using a dynamic variable to test the results of a method that returns an anonymous type - more specifically it returns a JsonResult, which as json looks like this

{ "newData" : [ 1120741.2697475906,
      826527.64681837813
    ],
  "oldData" : [ 1849870.2326665826,
      1763440.5884212805
    ],
  "timeSteps" : [ 0,
      4.8828124999999998e-10
    ],
  "total" : 2
}

I can read the JSonResult which will give me the anonymous type. Here's my code:

var jsonResult = controller.GetChangeData(1) as JsonResult;
dynamic data = jsonResult.Data;
Assert.AreEqual(2, data.total); // This works fine :)

But how do I get at "newData" for example? This code....

var newData = data.newData;

Gives me a System.Linq.Enumerable.WhereSelectArrayIterator, but I don't know what to do with it to be able to just use it as an arry of doubles.

I tried casting it as a double[], but it doesn't work either.

As an aside, can I easily check if a property is defined on the dynamic?

2
  • What happens when you try this data.newData.ToArray()? Commented Nov 12, 2010 at 12:46
  • var data2 = data.newData.ToArray(); --- > 'object' does not contain a definition for 'ToArray' (tried with some casts too) Commented Nov 12, 2010 at 12:49

3 Answers 3

3

The reason .ToArray() doesn't work is that it's an extension method, and extension methods aren't available at runtime. That just means you have to call the function statically. Does Enumerable.ToArray<double>(data.newData) work?

You may need Enumerable.ToArray(Enumerable.Cast<double>(data.newData)) depending on what elements newData actually has.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes! Enumerable.ToArray<double>(data.newData) does the job for me :) Thanks
2

To get the properties of an instance of a dynamic type

PropertyDescriptorCollection props = TypeDescriptor.GetProperties(dyn);
foreach (PropertyDescriptor prop in props)
{
  object val = prop.GetValue(dyn);
  var propName = prop.Name;
  var propValue = val;
}

where dyn is an instance of a dynamic object.

1 Comment

This was a helpful copy+pastable nugget of code, that I'm pretty sure is going to become an extension method at work...
1

Could you use the JavaScriptSerializer class to parse the Json string into a dynamic variable? Eg:

var serializer = new JavaScriptSerializer();
var jsonObj = serializer.Deserialize<dynamic>(jsonString);
var newData1 = jsonObj["newData"][0];

1 Comment

+1 for a working answer. The prob with this is since my json was in a JsonResult, I needed to Serialize it to a string and then deserialize it back into a dynamic, so less ideal.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.