7

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.

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

  2. 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.

Pure.Krome
  • 84,693
  • 113
  • 396
  • 647
  • Related: http://stackoverflow.com/questions/2974008/adding-unknown-at-design-time-properties-to-an-expandoobject – Steven Feb 13 '12 at 11:23

1 Answers1

12

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 ...
Pure.Krome
  • 84,693
  • 113
  • 396
  • 647
Henrik Gering
  • 1,769
  • 16
  • 29
  • 1
    henrik, looked thro that expandoobject() stuff a while back. i can't help but agree with 'bob's' observations on it: http://blogs.msdn.com/b/csharpfaq/archive/2009/10/01/dynamic-in-c-4-0-introducing-the-expandoobject.aspx#10003637 – jim tollan Feb 13 '12 at 14:04