I'm trying to create a some Json in my MVC app and I only want to include the properties from my source object, if it has some properties values, set.
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 };
Dddd only has been set.
return Json(new { Dddd = source.Dddd }
See how i was trying to create an anonymous object on the fly. Well, I can do that because in this contrite example, I know what was set. But when it comes to real code, I would have to do 'figure out' what was really set and then dynamically return that.
The idea is based upon Stack Exchange's Api Wrapper .. where they have some optional values that they return via json, if they are set.
var x = new ExpandoObject(); x. AddProperty("NewProp", System. String);
In C++, the objects can be created at run-time. C++ supports two operators new and delete to perform memory allocation and de-allocation. These types of objects are called dynamic objects. The new operator is used to create objects dynamically and the delete operator is used to delete objects dynamically.
Take a look at the ExpandoObject, an example with xml is given here
eg.
dynamic contact = new ExpandoObject();
contact.Name = "Patrick Hines";
contact.Phone = "206-555-0144";
... etc ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With