Click here to Skip to main content
13,836,160 members
Click here to Skip to main content
Add your own
alternative version


37 bookmarked
Posted 29 Apr 2009
Licenced CPOL

Custom JSON Serializer for the Entity Framework

, 29 Apr 2009
Rate this:
Please Sign up or sign in to vote.
Custom JSON serializer for the Entity Framework


Entity Framework’s entity (which has a relationship with other entities) cannot serialize with .NET Framework’s existing object like JavascriptSerializer or DataContract JSON Serializer or JsonResult. So I needed to solve that problem by myself.


In one of our projects, we used ASP.NET MVC for presentation/business logic layer and Entity framework for data access layer. At that time I faced the problem. I needed to call server side methods from client side JavaScript with the help of XMLHttp request. In the client side, we used JQuery (JavaScript library). The server side methods needed to return data with Jason format. At first I tried to use JsonResult (MVC framework) to transform that data to JSON format, then one error message was thrown. The error message was “Circular Reference error”. Then I used JavascriptSerializer class. But the same thing occurred. Then I tried DataContract JSON Serializer. I got the same error once again.

I was wondering what I should do. I first started Googling to solve my problem. There I found that Entity framework’s Entity serialization had some problem with the existing JSON Serializer provided by the .NET Framework. So, I started thinking of writing my own small serializer to solve and use Entity framework with JSON.


public class CustomJSonSerializer

public static string JsonSerialize<T>(T obj) where T : class
    var sb = new StringBuilder("{");

    var parentType = obj.GetType(); // I get type from given object 

    // use reflection to retrieve all properties of that type
    var ms = parentType.GetMembers().Where(v => v.MemberType 
        == MemberTypes.Property).ToList<MemberInfo>();

    const string doubleQuote = "\"";
    var counter = 0;
    var stringTypes = new List<String> { "String", "Guid", 
        "Boolean" };

    //Following Types are used by Entity Framework. So no need to 
    //serialize those types.
    var ignoreEntityTypes = new List<String> { "EntityReference`1", 
        "EntityCollection`1", "EntityState", 
        "EntityKey", "EntitySetName" };

    //Start iteration to navigate each property
    foreach (PropertyInfo p in ms)
        var propertyName = p.Name;
        var propertyType = p.PropertyType;
        var propertyValue = p.GetValue(obj, null);

        //If property type is matched with ignoreTypes then
        //goto next loop
        if (ignoreEntityTypes.Contains(propertyType.Name))

        if (stringTypes.Contains(propertyType.Name))
            if (propertyValue == null)
                sb.Append(doubleQuote + propertyName + doubleQuote + 
                          ":" + "null");

                sb.Append(doubleQuote + propertyName + doubleQuote + 
                    ":" + doubleQuote + propertyValue.ToString() + doubleQuote);

        else if (propertyType != null && propertyType.IsPrimitive)
            sb.Append(doubleQuote + propertyName + doubleQuote 
                + ":" + propertyValue.ToString());

        //Still I have doubt how Date Time will be handled.
        else if (propertyType.Name == "DateTime")
            var dt = (DateTime)propertyValue;
            sb.Append(doubleQuote + propertyName 
                + doubleQuote + ":" 
                + "new Date(" + dt.Ticks.ToString() + ")");
            if (propertyValue != null)
                sb.Append(doubleQuote + propertyType.Name + doubleQuote + ":");
                //If property value is another entity, then
                //call the method recursively.
        //If it is not the last property, then add comma
        if (counter < ms.Count)
    var result = sb.ToString().Replace(",}", "}");
    return result;


I did not test it with very complex scenarios. So issues may arise. Still, I do not know how the JSON Serializer handles datetime. I use the Tick property of the DateTime method. It may be incorrect.


I solved my problem in this way. I hope it will work for you if you need to work with Entity framework and JSON format.


  • 29th April, 2009: Initial post


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

S. M. Ahasan Habib
Bangladesh Bangladesh
I believe in and stay with living-learning culture. I believe learning is fun. I feel coding is like poetry. I am work with various technologies in my professional career (AngularJS, ASP.NET MVC/WebAPI, Scala-Play Framework, Nodejs, SharePoint, Redshift).

You may also be interested in...

Comments and Discussions

AnswerGreat Post! Pin
tanweer7-May-14 3:19
membertanweer7-May-14 3:19 
Generalthank you for sharing Pin
gjllyl19-Feb-14 19:16
membergjllyl19-Feb-14 19:16 
QuestionThanks alot! Pin
Mr.thang25-Mar-13 23:59
memberMr.thang25-Mar-13 23:59 
GeneralMy vote of 5 Pin
Аslam Iqbal24-Feb-13 0:35
professionalАslam Iqbal24-Feb-13 0:35 
QuestionAny Update on Json Serializer [modified] Pin
josehidalgor15-Jul-11 14:39
memberjosehidalgor15-Jul-11 14:39 
GeneralAn unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll Pin
62316e2-Nov-09 19:18
member62316e2-Nov-09 19:18 
GeneralGreat Article. Pin
Razan Paul (Raju)7-Jun-09 22:09
memberRazan Paul (Raju)7-Jun-09 22:09 
GeneralThanks for sharing Pin
jawwadalam2-Jun-09 4:53
memberjawwadalam2-Jun-09 4:53 
GeneralGood Pin
Alexandru Cibotari16-May-09 4:34
memberAlexandru Cibotari16-May-09 4:34 
GeneralRe: Good Pin
S. M. Ahasan Habib16-May-09 20:42
professionalS. M. Ahasan Habib16-May-09 20:42 
GeneralGood work Pin
setu_raas29-Apr-09 20:16
membersetu_raas29-Apr-09 20:16 
GeneralRe: Good work Pin
S. M. Ahasan Habib29-Apr-09 20:23
professionalS. M. Ahasan Habib29-Apr-09 20:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01 | 2.8.190114.1 | Last Updated 29 Apr 2009
Article Copyright 2009 by S. M. Ahasan Habib
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid