JSON serialize Entity Framework objects

asp.net-ajax entity-framework json wcf


It seems that neither the native DataContractJsonSerializer in WCF nor the native JavaScript serializer in ASP.NET can serialize Entity Framework objects into JSON. This is because both serializers reject references counting problems. Additionally, I attempted Json.NET, which likewise fails explicitly due to a Reference Counting problem.

Edit: Now, Json.NET supports synchronize serial and deserial Entries in the Entity Framework.

I want to expose a platform-agnostic API, thus my objects are Entity Framework objects that are overloaded to carry out extra business functions (such as authentication, etc.). I do not want to adorn these classes with platform-specific characteristics, etc.

I really wrote a blog post at https://blog.programx.co.uk/2009/03/18/wcf-json-serialization-woes-and-a-solution/ detailing each step I took.

Have I overlooked anything simple?

11/22/2017 3:16:48 PM

Accepted Answer

In order to do this, I project the data I wish to serialize into an anonymous type before serializing it. By doing this, I can make sure that just the data that I truly need in the JSON gets serialized and that nothing else in the object tree is accidentally serialized. It appears as follows:

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

I almost think anonymous sorts are perfect for this. The JSON, obviously, doesn't care what type was used to produce it. Additionally, you have total freedom in deciding what features and structures to include in the JSON thanks to anonymous types.

3/18/2009 12:30:06 PM

Popular Answer

Microsoft erred while converting EF objects into data contracts. They also included the back linkages and the basic classes.

For each of the entities you wish to return, your best approach is to create comparable Data Transfer Object classes. These would merely consist of the data, leaving out the behavior and entity-specific EF components. Additionally, you would provide methods for converting from and into your DTO classes.

The Data Transfer Objects would then be returned by your services.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow