3

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;
    } 
JohanLarsson
  • 475
  • 1
  • 8
  • 23
  • Why don't you want to deserialize them into [`dynamic` from the start](http://stackoverflow.com/questions/4535840/deserialize-json-object-into-dynamic-object-using-json-net)? Or is there a requirement that you have to use `JArray` initially? – Eugene Podskal Mar 13 '16 at 10:55
  • No, I don't have to use a JArray. How would I do otherwise, saw your link but not sure how to apply this? I've tried to take a IList in the web api controller signature but that did not work. However I've been told that JArray is more portable though... – JohanLarsson Mar 13 '16 at 11:02

1 Answers1

2

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();
Jordan Ryder
  • 2,336
  • 1
  • 24
  • 29