Best way to convert a JArray object to a List of dynamic ExpandoObjects

Viewed 2897

Our angularjs spa is sending a list of dynamic objects to our backend. I've read that the best way to receive such a list is to use a JArray. Since our business layer is built to receive a list of dynamic objects I need to convert the array.

For this reason I'm wondering what is the quickest and best way to convert the JArray object to dynamic List. Here is what I've come up with so far, using an exension that I am intending to use where needed..

This works but I'm not sure if its efficient when the array contains many objects?

    public static IList<dynamic> ToDynamicList(this JArray data)
    {
        var dynamicData = new List<dynamic>();
        var expConverter = new ExpandoObjectConverter();

        foreach (var dataItem in data)
        {
            dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(dataItem.ToString(), expConverter);
            dynamicData.Add(obj);
        }
        return dynamicData;
    } 
1 Answers

Same here, I use standard methods that give me JArrays. Sometimes I want to convert them to dynamics depending on what I'm doing. Here's what I did.

//JArray data
List<dynamic> dlist = data.Select(d => (dynamic)d).ToList();
Related