私がやりたいことは、オブジェクト構造(たとえば、Entity Frameworkオブジェクト)を取り、それを動的オブジェクトに変換し(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);
}
}