是否有可能在飞行中创建属性,用.NET动态对象?有可能、属性、对象、动态

2023-09-04 23:58:07 作者:最初的苍老

我想在我的MVC应用程序创建一些JSON和我只是想从我的源对象包括的属性,如果它有一些属性值设置。

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.

如:

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

//例输出。

AAAA级和CCCCC只值: 返回JSON(新{AAAA级= source.Aaaa,CCCC = source.Ccccc.Value};

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

DDDD唯一还没有确定。 返回JSON(新{DDDD = source.Dddd}

Dddd only has been set. return Json(new { Dddd = source.Dddd }

看我怎么试图动态创建一个匿名对象。好吧,我能做到这一点,因为在这种懊悔的例子,我知道发生了什么设置。但是,当涉及到实际code,我会做弄清楚什么是真正集,然后动态地返回。

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.

我们的想法是基于堆栈交易所的API包装 ..他们在那里,他们通过JSON返回一些可选值,如果它们被设定

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.

推荐答案

看看的的 ExpandoObject ,使用XML给出一个例子here

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

如:

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