Json Serializer for MVC

Posts   
 
    
Posts: 134
Joined: 10-Jan-2007
# Posted on: 19-Jan-2009 22:10:58   

Classes (Both work with Adapter and SelfServicing) to

  1. Serialize/Deserialize LLBLGen entities in the MVC using the built in JavaScriptSerializer

Usage

Serialize: Use the extension method to call ToJson directly on an Entity (entity.ToJson(); ) Deserialize: CompanyEntity company = LLBLGenWebExtension.FromJson<CompanyEntity>(jsonstring);

Notes

The Deserialize sets IsNew if a primary key field is set to a meaningful value (for ints > 0, strings not blank, etc.). You can change this behaviour by providing your own form field (i.e. company.IsNew) AND removing the "IsNew" from the list of excluded fields

The serializer only follows relations where the entity is on the PK Side, this keeps circular references from spinning out.

  1. Return a JsonResult from action methods using the serializer.

Usage ===== Returns LLBLGen objects serialized to Json from MVC action methods.

Add the LLBLGenJsonResult.cs AND LLBLGenJavaScriptConverter.cs to your project

You will be able to return Json from mvc controller methods:

    [AcceptVerbs(HttpVerbs.Get)]
    public ActionResult Edit(int id)
    {
        CompanyEntity company = new CompanyEntity(id);
        new DataAccessAdapter().FetchEntity(company);
        return new LLBLGenJsonResult(company);
    }

Notes

This class may not be necessary if the MVC team can parse the current config file settings for adding a custom converters.

Brian

Attachments
Filename File size Added on Approval
LLBLGenJson.zip 3,505 19-Jan-2009 22:11.23 Approved
daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 20-Jan-2009 07:12:18   

Thanks for the contribution Brian!

David Elizondo | LLBLGen Support Team
Otis avatar
Otis
LLBLGen Pro Team
Posts: 39613
Joined: 17-Aug-2003
# Posted on: 20-Jan-2009 09:59:17   

You're on a roll! smile

Frans Bouma | Lead developer LLBLGen Pro
bmoeskau
User
Posts: 54
Joined: 15-Jun-2005
# Posted on: 19-Sep-2009 09:25:51   

Brian,

Your code looks promising -- this is exactly what I am looking for. Since it was posted back in January, I thought I would ask if you've made any updates since then. Specifically I am looking for the ability to serialize an entire EntityCollection without having to write a loop and build an array of individually-serialized entities. While I could do that (or better, modify your code to support EntityCollection.ToJson()) I figured I would check to see if that's something you've already tackled.

Frans (if you see this) -- I have read other threads where you've commented that you don't plan to specifically support JSON serialization, and I understand your wanting to focus on the core LLBL functionality. However, I think there's a strong case to be made that JSON has already become the de facto data standard for modern web applications. I saw that LLBL supports XML serialization out of the box and was surprised to find out that JSON was not also supported. As time goes by more and more web developers will be asking for this, and it would be nice to have an officially supported (or at least recommended) solution for this. Getting a recursion error out of the box when attempting to use standard JSON libs against an entity (JSON.Net does this too, it's not just an MS issue) is not good, even if it's not "your fault." There's got to be a better way. simple_smile

Thanks, Brian

Posts: 134
Joined: 10-Jan-2007
# Posted on: 20-Sep-2009 21:32:17   

The code should already work with collections. The ToJson extension just creates a standard JavaScriptSerializer and registers the Converter. The MS serializer is responsible for for creating and calling the correct converter. The serializer should see the EntityCollection as IEnumerable and create an array, then call this converter for each element.

So this should work:

LLBLGenWebExtension.CreateJavaScriptSerializer().Serialize(yourEntityCollection);

Adding an extension to the attached source would be:

public static string ToJson(this IEntityCollection coll)
{
        return CreateJavaScriptSerializer().Serialize(coll);
}

For Deserialize, any Json array comes out as an IList (I believe), which can then be used to construct an EntityCollection.

As to your comments on LLBLGen supporting more serialization techniques, I totally agree, I have had issues "selling" LLBLGen because folks want to use the latest/"greatest". IMHO, LLBLGen is the best of the best for O/R mappers out there. The smallest inputs reap incredible productivity gains.

A lot of developers out there are looking for frictionless integration with all the MS frameworks and having LLBLGen not support them "out of the box" causes it to get passed up. Even though MS tools have issues, many will not look at other tools if a feature is not on the datasheet.

I also understand that Frans and team are not able to create and support the myriad of changing technologies coming out of MS. Expecially when they keep changing their mind. wink

Frans has been very supportive of community members adding support (I have also added support for ADO.NET Data Services IUpdateable and the ASP.NET MVC Model Binder). However, finding solutions to these in the forums is not always easy. Many threads just end with "we do not want to support x feature, but you can add it yourself". This is dissapointing because you just need to get something working and having to fight your way through sucks.

It would be nice if we (as a community) could get together and add more formalized support on top of LLBLGen and then have Frans and co make them available as "recommended" solutions, not just links back to other forum threadssimple_smile

I am sure many of the things we need done will be a lot easier to do and share with the 3.0 release.

Brian

Posts: 134
Joined: 10-Jan-2007
# Posted on: 10-Nov-2009 16:24:51   

Had code to ensure circular references not followed but turns out not needed during Deserialize since it checks for property existence before trying to create.

Updated code attached.

Brian

Attachments
Filename File size Added on Approval
LLBLGenJson.zip 3,611 10-Nov-2009 16:24.59 Approved
smurrell
User
Posts: 59
Joined: 22-Feb-2007
# Posted on: 27-Mar-2013 22:52:32   

brianchance wrote:

Had code to ensure circular references not followed but turns out not needed during Deserialize since it checks for property existence before trying to create.

Updated code attached.

Brian

Do you have an updated version to allow a TypedList to be serialized to Json or the TypedList's row?

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39613
Joined: 17-Aug-2003
# Posted on: 28-Mar-2013 11:08:31   

Typed lists / views are datatables, I think JSON.NET serializes them properly?

Frans Bouma | Lead developer LLBLGen Pro
smurrell
User
Posts: 59
Joined: 22-Feb-2007
# Posted on: 28-Mar-2013 11:30:22   

Below is code which I wrote eventually to convert a DataSet to Json. Ignores circular references.


            // Initialize Class
            string jsonResult = JsonConvert.SerializeObject(records.Tables[0],
                Formatting.Indented,
                new JsonSerializerSettings()
                {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                });
            // Return
            return new ContentResult { Content = jsonResult, ContentType = "application/json" };
Otis avatar
Otis
LLBLGen Pro Team
Posts: 39613
Joined: 17-Aug-2003
# Posted on: 28-Mar-2013 14:48:10   

Thanks for sharing.

Frans Bouma | Lead developer LLBLGen Pro