Is it possible to create properties on the fly using a dynamic .NET object?

I am trying to create some kind of Json in my MVC application and I only want to add properties from the original object if it has some property values.

eg.

public class Foo { public string Aaaa { get; set; } public string Bbbb { get; set; } public int? Ccccc { get; set; } public Lol Dddd { get; set; } } 

// Example Outputs.

  • Aaaa and Ccccc have values ​​only: return Json(new { Aaaa = source.Aaaa, Cccc = source.Ccccc.Value };

  • Only dddd is installed. return Json(new { Dddd = source.Dddd }

See how I tried to create an anonymous object on the fly. Well, I can do this because in this crushing example, I know what was installed. But when it comes to real code, I will need to “find out” what is really installed, and then dynamically return it.

The idea is based on the Stack Exchange Api Wrapper , where they have some optional values ​​that they return via json, if installed.

+7
source share
1 answer

Take a look at ExpandoObject , an example with xml is here

eg.

 dynamic contact = new ExpandoObject(); contact.Name = "Patrick Hines"; contact.Phone = "206-555-0144"; ... etc ... 
+11
source

All Articles