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

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

问题描述

看来,序列化框架的实体对象到JSON是不可能使用任何WCF的本地DataContractJsonSerializer或ASP.NET的本地JavaScript串行器。这是因为引用计数问题都拒绝序列化器。我也曾尝试 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现在可以<一个href=\"http://james.newtonking.com/archive/2009/07/10/ado-net-entity-framework-support-accidently-added-to-json-net.aspx\"相对=nofollow>序列化和反序列化实体框架的实体的。

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

我的对象是实体框架对象,重载执行额外的业务功能(如身份验证等),我不希望因为我想$ P $与特定于平台的属性,等来装饰这些类psent一个平台无关的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/blogs/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

我错过了一些东西明显?

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天全站免登陆