开发者

How to read properties from anonymous types using "dynamic" variable

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.Enu开发者_JAVA百科merable.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?


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.


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.


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];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜