将实体框架对象序列化为JSON [英] Serialize Entity Framework objects into JSON

查看:188
本文介绍了将实体框架对象序列化为JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎使用WCF的本机DataContractJsonSerializer或ASP.NET的本机JavaScript序列化程序将Entity Framework对象序列化为JSON是不可能的。这是由于序列化程序拒绝的引用计数问题。我也尝试过 Json.NET ,它也没有专门针对参考计数问题。

It seems that serializing Entity Framework objects into JSON is not possible using either WCF's native DataContractJsonSerializer or ASP.NET's native JavaScript serializer. This is due to the reference counting issues both serializers reject. I have also tried Json.NET, which also fails specifically on a Reference Counting issue.

编辑: Json.NET现在可以序列化和反序列化实体框架实体

Json.NET can now serialize and deserialize Entity Framework entities.

我的对象是实体框架对象,它们被重载以执行其他业务功能(例如,认证等等),我不想用平台特定的属性等装饰这些类,因为我想提出一个不知不觉间的API。

My objects are Entity Framework objects, which are overloaded to perform additional business functionality (eg. authentication, etc.) and I do not want to decorate these classes with platform-specific attributes, etc. as I want to present a platform-agnostic API.

我有实际上是关于我在 http://bloggingabout.net/b logs / program.x / archive / 2009/03/18 / wcf-json-serialization-woes.aspx

I've actually blogged about the individual steps I went though at http://bloggingabout.net/blogs/program.x/archive/2009/03/18/wcf-json-serialization-woes.aspx

我有没有想过明显的东西? p>

Have I missed something obvious?

推荐答案

我这样做的方式是将我要序列化的数据投射到一个匿名类型并序列化。这确保只有我在JSON中实际需要的信息是序列化的,并且我不会无意中将对象图形进一步序列化。它看起来像这样:

The way I do this is by projecting the data I want to serialize into an anonymous type and serializing that. This ensures that only the information I actually want in the JSON is serialized, and I don't inadvertently serialize something further down the object graph. It looks like this:

var records = from entity in context.Entities
              select new 
              {
                  Prop1 = entity.Prop1,
                  Prop2 = entity.Prop2,
                  ChildProp = entity.Child.Prop
              }
return Json(records);

我发现匿名类型是理想的。显然,JSON并不在乎使用什么类型来生成它。匿名类型可以让您完全灵活地了解您将JSON放入哪个属性和结构。

I find anonymous types just about ideal for this. The JSON, obviously, doesn't care what type was used to produce it. And anonymous types give you complete flexibility as to what properties and structure you put into the JSON.

这篇关于将实体框架对象序列化为JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆