将 EF 模型序列化为 Json 时的循环引用 [英] Circular reference while serializing EF model to Json
问题描述
我知道有很多与此主题相关的问题,但没有一个能解决我的问题.
I know that are tons of questions related to this topic all over SO but none of them solved my problem.
我将 MVC 5 与 Entity Framework 6 和 Newtonsoft.Json 一起使用.
I'm using MVC 5 with Entity Framework 6 and Newtonsoft.Json.
我有这个异常的常见场景:
I have the usual scenario for this exception:
Service => Staff => Service
当我尝试在我的视图中序列化一个 service
对象时,如下所示:
When I try to serialize a service
object in my view, like this:
var arr = @Html.Raw(@JsonConvert.SerializeObject(Model.Services));
我收到在序列化类型为...的对象时检测到循环引用...
"异常.
我在这里找到的所有答案都说解决起来很麻烦,我应该添加
All the answers I found here say it is wasy to solve, I should just add
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings
.PreserveReferencesHandling = PreserveReferencesHandling.All;
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings
.ReferenceLoopHandling = ReferenceLoopHandling.Serialize;
在我的 Global.asax
文件中.
好吧,我做到了,但它不起作用.我在 MSDN 上读了很多文章,他们都说同样的话.我不知道为什么,但它对我不起作用.
Well, I did, and it just doesn't work. I read a bunch of articles on MSDN an they all say the same thing. I don't know why, but it just doesn't work for me.
我可以让它工作的唯一方法是在我的控制器中创建整个序列化上下文:
The only way I could make it work, was to create the whole serialization context in my controller:
var settings = new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.All,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize
};
var serializer = JsonSerializer.Create(settings);
var msmStream = new MemoryStream();
var txtWriter = new StreamWriter(msmStream);
var writer = new JsonTextWriter(txtWriter) { Formatting = Formatting.Indented };
serializer.Serialize(writer, services);
var json = Encoding.ASCII.GetString(msmStream.GetBuffer());
然而,这是一个糟糕的解决方案,特别是如果我正在视图中动态地从我的视图模型中序列化一个属性.这也违背了全局配置"的全部目的.
However, this is a terrible terrible solution, specially if I'm serializing a property from my view model on the fly in the view. It also defeats the whole purpose of a "global configuration".
有人遇到过这个问题吗?
Has anybody faced this problem?
推荐答案
您需要将 DefaultSettings 更改为新的.
You need to change the DefaultSettings to new ones.
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.All,
ReferenceLoopHandling = ReferenceLoopHandling.Serialize
};
来源
这篇关于将 EF 模型序列化为 Json 时的循环引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!