Creating dynamic arrays and lists using Dynamic and ExpandoObject in C#

In this previous post, C# Using Newtonsoft and dynamic ExpandoObject to convert one Json to another, I described how you can use the dynamic keyword and the ExpandoObject class to quickly transform JSON without the need for any concrete implementations of either the source or destination JSON.

This is an example of a dynamic list where you do not know the number of objects in the output array:

dynamic output = new List<dynamic>();

dynamic row = new ExpandoObject();
row.NAME = "My name";
row.Age = "42";
output.Add(row);

USAGE IN REAL LIFE:

Imagine you need to convert the following JSON by taking only those rows where the age is above 18:

{
	"attributes": [{
			"name": "Arthur Dent",
			"age": 42,
		},
		{	"name": "Ford Prefect",
			"age": 1088,
		},
		{	"name": "Zaphod Beeblebrox",
			"age": 17,
		}]
}

The code to transform the JSON would look something like this:

// Convert input JSON to a dynamic object
dynamic input = JsonConvert.DeserializeObject(myQueueItem);

// Create a list of dynamic object as output
dynamic output = new List<dynamic>();

foreach (var inputAttribute in input.attributes)
{
  if (inputAttribute.Age >= 18)
  {
    // Create a new dynamic ExpandoObject
    dynamic row = new ExpandoObject();
	row.name = inputAttribute.name;
	row.age = inputAttribute.age;
	// Add the object to the dynamic output list
	output.Add(row);
  }
}

// Finally serialize the output array
string outputJson = JsonConvert.SerializeObject(output);

The output is this:

[
  {  "name": "Arthur Dent",
	 "age": 42,
  }, 
  {	 "name": "Ford Prefect",
	 "age": 1088,
  }
]

MORE TO READ:

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in .net, c#, General .NET and tagged , , , . Bookmark the permalink.

3 Responses to Creating dynamic arrays and lists using Dynamic and ExpandoObject in C#

  1. Swatantra Singh says:

    Great insights Brian.
    Can throw another example where the list properties are derived from Json response?

    Like

  2. Pingback: C# Deserialize JSON to dynamic ExpandoObject() | Brian Pedersen's Sitecore and .NET Blog

  3. Pingback: C# Convert XML to JSON using dynamic ExpandoObject, XDocument and NewtonSoft.JSON | Brian Pedersen's Sitecore and .NET Blog

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.