Click here to Skip to main content
6,629,885 members and growing! (22,130 online)
Email Password   helpLost your password?
Web Development » ASP.NET » Samples     Beginner License: The Code Project Open License (CPOL)

Custom JSON Serializer for the Entity Framework

By Ahasanhabib

Custom JSON serializer for the Entity Framework
C#, .NET, ASP.NET, ADO.NET, Ajax, Architect, Dev, QA
Version:4 (See All)
Posted:29 Apr 2009
Views:5,290
Bookmarked:18 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
7 votes for this article.
Popularity: 3.91 Rating: 4.63 out of 5

1

2
1 vote, 14.3%
3
1 vote, 14.3%
4
5 votes, 71.4%
5

Introduction

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.

Background

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.

Solution

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)
    {
        counter++;
        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))
        {
            continue;
        }

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

            else
            {
                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() + ")");
        }
        else
        {
            if (propertyValue != null)
            {
                sb.Append(doubleQuote + propertyType.Name + doubleQuote + ":");
                //If property value is another entity, then
                //call the method recursively.
                sb.Append(JsonSerialize(propertyValue));
            }
            else
            {
                continue;
            }
        }
        //If it is not the last property, then add comma
        if (counter < ms.Count)
        {
            sb.Append(",");
        }
    }
    sb.Append("}");
    var result = sb.ToString().Replace(",}", "}");
    return result;
}

Limitation

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.

Conclusion

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.

History

  • 29th April, 2009: Initial post

License

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

About the Author

Ahasanhabib


Member
S. M. Ahasan Habib is a Software Engineer with over 6 years of Software Development experience. He has been working with both for local and overseas clients. He is proficient in all phases of Software Development Lifecycle and specializes in distributed application design, development, data modeling and application trouble shooting. He is basically Microsoft technology lover.
Occupation: Software Developer (Senior)
Company: Azolve Technologies Bangladesh Ltd
Location: Bangladesh Bangladesh

Other popular ASP.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 7 of 7 (Total in Forum: 7) (Refresh)FirstPrevNext
GeneralAn unhandled exception of type 'System.StackOverflowException' occurred in mscorlib.dll Pinmember62316e19:18 2 Nov '09  
GeneralGreat Article. PinmemberRazan Paul (Raju)22:09 7 Jun '09  
GeneralThanks for sharing Pinmemberjawwadalam4:53 2 Jun '09  
GeneralGood PinmemberAlexandru Cibotari4:34 16 May '09  
GeneralRe: Good PinmemberAhasanhabib20:42 16 May '09  
GeneralGood work Pinmembersetu_raas20:16 29 Apr '09  
GeneralRe: Good work PinmemberAhasanhabib20:23 29 Apr '09  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 29 Apr 2009
Editor: Deeksha Shenoy
Copyright 2009 by Ahasanhabib
Everything else Copyright © CodeProject, 1999-2009
Web18 | Advertise on the Code Project