我想输出一个使用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