Serialize Entity Framework objects into 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);

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.

Leave a Comment