我想要做的是采用对象构造(例如,Entity Framework对象),然后将其转换为动态对象(Thinking JSON.Net JObject可能是最合适的),并扩展所述对象具有用于发送到客户端的其他属性或视图模板。
dynamic model = JS.ToJObject(myConcreteInstance);
model.AdditionalValue = "I need this stuff on the client... ";
这是我拥有的,有效的,但宁可没有try / catch。
//JS.ToJObject
public static JObject ToJObject(object input)
{
try {
//anonymous types throw an exception here
// Could not determine JSON object type for type f__AnonymousType ...
return new JObject(input);
} catch(Exception) {
//fallback to serialize/deserialize, which seems wasteful
var txt = JsonConvert.SerializeObject(
input
,new IsoDateTimeConverter()
,new DataTableConverter()
,new DataSetConverter()
);
return JObject.Parse(txt);
}
}