0

I have an endpoint that allows me to get the top node of my graph. I also allow the client to specify the nodes he wishes to retrieve that are children of the top node:

For example:

/libraries/5?with=banner|videos

This will retrieve me a library with a banner object and a list of videos.

I provide a full query language, that supports nesting. For example if you wanted the same structure but including the covers and chapters for each video you would request this:

/libraries/5?with=banner|videos[cover|chapters]

I need to build the object dynamically when the request comes in. I have had a look at Clay, but the project seems a little old, and I am sure there is a better way to build objects at runtime than using ExpandoObject.

If anyone has any ideas, I would be most grateful?

joepour
  • 6,831
  • 10
  • 32
  • 29

2 Answers2

0

ExpandoObject is the way to go for assigning dynamic properties to an object.

You could use Dictionary but the code can get ugly. Consider the following example -

Dictionary<string, object> parent = new Dictionary<string, object>();
parent["known_prop"] = new List<object>();    
parent["dynamic_prop"] = new Dictionary<string, object>();
parent["dynamic_prop"]["some_value"] = new List<object>();

The same can be written in a very concise way in ExpandoObject -

var a = new ExpandoObject();
a.Prop1 = new List<Object>();
a.Prop2 = new ExpandoObject();
a.Prop2.Val = new List<Object>();
JunaidKirkire
  • 878
  • 1
  • 7
  • 17
0

C# is not so good in dynamic objects which is by design - its statically typed language. There is a dynamic type that emulates static access to otherwise dynamic (unknown at compile time) structure. You can use it to assign and retrieve values.

If by endpoint you understand so web service that returns json or xml then you do not need to create dynamic object just build the expected structure. Newtonsoft json serializer for-instance can nicely serialize dictionary:

_dictionary.Add("banner", new Banner())

will produce

{
    "banner" : { ... banner properties ... }
}
Rafal
  • 12,391
  • 32
  • 54