我想輸出一個使用DataContractJsonSerializer類的json格式的對象列表,但我一直運行到下面的錯誤。DataContractResolver/KnownType問題當自定義類包含另一個自定義類
Type 'Castle.Proxies.JokeCategoryProxy' with data contract name
'JokeCategoryProxy:http://schemas.datacontract.org/2004/07/Castle.Proxies'
is not expected. Consider using a DataContractResolver or add any types not
known statically to the list of known types - for example, by using the
KnownTypeAttribute attribute or by adding them to the list of known
types passed to DataContractSerializer.
我知道這已被回答之前,但它似乎只發生在我的對象有一個屬性是另一個自定義對象。
[DataContract]
[KnownType(typeof(ModelBase<int>))]
public class Joke : ModelBase<int>
{
[DataMember]
public virtual string JokeText { get; set; }
[DataMember]
public virtual JokeCategory JokeCategory { get; set; }
}
[DataContract]
[KnownType(typeof(ModelBase<int>))]
public class JokeCategory : ModelBase<int>
{
[DataMember]
public virtual string Name { get; set; }
}
正如你所看到的笑話模型包含一個笑話類對象,如果我刪除的笑話範疇,只是有一個int(JokeCategoryId)錯誤消失,雖然一個解決方案,而不是一個理想的,因爲我想使分類可用而不必再次查詢。
下面是我使用生成JSON
public static ContentResult JsonResponse<TReturnType>(this Controller controller, TReturnType data)
{
using (var oStream = new System.IO.MemoryStream())
{
new DataContractJsonSerializer(typeof(TReturnType)).WriteObject(oStream, data);
return new ContentResult
{
ContentType = "application/json",
Content = Encoding.UTF8.GetString(oStream.ToArray()),
ContentEncoding = Encoding.UTF8
};
}
}
什麼混淆我最深的是,錯誤引用Castle.Proxies.JokeCategoryProxy(誰知道這個來自?)
代碼有什麼建議嗎?
非常有用的東西sJhonny。目前我不會進入DTOs,但我會記住它們以備未來發展。在流暢的nhibernate映射文件中使用.Not.LazyLoad()可以完美地解決即時問題。非常感謝你。 – JConstantine