Products

Solutions

Resources

Partners

Community

About

New Community Website

Ordinarily, you'd be at the right spot, but we've recently launched a brand new community website... For the community, by the community.

Yay... Take Me to the Community!

The Community Blog is a personal opinion of community members and by no means the official standpoint of DNN Corp or DNN Platform. This is a place to express personal thoughts about DNNPlatform, the community and its ecosystem. Do you have useful information that you would like to share with the DNN Community in a featured article or blog? If so, please contact .

The use of the Community Blog is covered by our Community Blog Guidelines - please read before commenting or posting.


DotNetNuke Tips and Tricks #22: ToJson or not ToJson

Over the last couple of years, I have been doing more and more work with JavaScript.  Whether it is work on web pages with jQuery or work in mobile applications with Appcelerator Titanium, I often find myself needing to transfer data to and from the server as JSON.  In DotNetNuke I frequently found myself constantly converting my .Net objects to and from JSON and it seemed to be a waste of time to constantly figure out what framework I should use to handle the JSON serialization/deserialization tasks. 

I have tried the JavaScriptSerializer,  the DataContractJsonSerializer  and even JSON.Net but I always keep coming back to the JavaScriptSerializer because it is the simplest solution that doesn’t impose any 3rd party dependencies.  The problem with all of these solutions is that I am constantly having to remember how to use them.  The API, even for the JavaScriptSerializer, still requires several lines of code whenever I want to use it.  I wanted something that was drop-dead simple, yet still powerful enough to handle 95% of my serialization/deserialization needs (for the really tough stuff I can still use one off code with an appropriate serializer)

Well, at some point I finally broke down and did what any good technologist would do – I turned to an expert who had already solved the problem in a simple, yet elegant way, and I copied him.  I have known Rick Strahl for several years and he is one of the few bloggers that I still find myself following on a regular basis.  I know that if I found the code useful, that it would also be pretty useful to many other DotNetNuke module developers as well.   Starting with DotNetNuke 5.4.3 we included a VB version of the JsonExtensionsWeb class from Rick’s original post (with Rick’s permission of course).

The JsonExtensionsWeb is simple extension class that adds several useful extension methods to any object.  Specifically it adds ToJson to any object and FromJson to any string. There are a couple of variations, depending on whether you are ok working with Generics (where the type must be known at compile time) or if you need a little more dynamic behavior (which is not supported natively by the JavaScriptSerializer).  Lets look at a few examples to get a feeling for the power and simplicity that this adds to our code.

There are occasions where you want to serialize an anonymous type without creating a concrete class to hold the type.  When working with web-services, I want to be able to keep my payload as small as possible and not send down a large serialized class if my client app only requires a small subset of properties from that class.  With these extensions I can create a simple anonymous class that only contains my needed data and then call the ToJson method to get a JSON string:

Dim json As String = _
  (New With { _
   .UserID = Me.UserInfo.UserID, _
   .UserName = Me.UserInfo.Username, _
   .Email = Me.UserInfo.Email}).ToJson()

Compare the JSON from my anonymous class versus if I had serialized the entire UserInfo object :

Anonymous = {"UserID":1, 
  "UserName":"host", 
  "Email":"host@change.me"}

UserInfo = {"AffiliateID":-1, "DisplayName":"SuperUser Account", "Email":"host@change.me", "FirstName":"SuperUser", "IsDeleted":false, "IsSuperUser":true, "LastIPAddress":null, "LastName":"Account", "Membership":{"Approved":true, "CreatedDate":"\/Date(1287064692000)\/", "IsOnLine":false, "LastActivityDate":"\/Date(1287240881730)\/", "LastLockoutDate":"\/Date(-6816268800000)\/", "LastLoginDate":"\/Date(1287240881687)\/", "LastPasswordChangeDate":"\/Date(1287065731593)\/", "LockedOut":false, "Password":null, "PasswordAnswer":null, "PasswordQuestion":null, "UpdatePassword":false, "Email":"host@change.me", "ObjectHydrated":false, "Username":"host"}, "PortalID":0, "Profile":{"Cell":null, "City":null, "Country":null, "Fax":null, "FirstName":"SuperUser", "FullName":"SuperUser Account", "IM":null, "IsDirty":false, "LastName":"Account", "Photo":null, "PhotoURL":"/dnnmobile/images/no_avatar.gif", "PostalCode":null, "PreferredLocale":"en-US", "ProfileProperties":[{"DataType":349, "DefaultValue":"", "IsDirty":false, "Length":50, "ModuleDefId":-1, "PortalId":-1, "PropertyCategory":"Name", "PropertyDefinitionId":1, "PropertyName":"Prefix", "PropertyValue":null, "Required":false, "ValidationExpression":"", "ViewOrder":1, "Visible":true, "DefaultVisibility":0, "Visibility":0, "CreatedByUserID":-1, "CreatedOnDate":"\/Date(-62135578800000)\/", "LastModifiedByUserID":-1, "LastModifiedOnDate":"\/Date(-62135578800000)\/"}, {"DataType":349, "DefaultValue":"", "IsDirty":false, "Length":50, "ModuleDefId":-1, "PortalId":-1, "PropertyCategory":"Name", "PropertyDefinitionId":2, "PropertyName":"FirstName", "PropertyValue":"SuperUser", "Required":false, "ValidationExpression":"", "ViewOrder":3, "Visible":true, "DefaultVisibility":0, "Visibility":0, "CreatedByUserID":-1, "CreatedOnDate":"\/Date(-62135578800000)\/", "LastModifiedByUserID":-1, "LastModifiedOnDate":"\/Date(-62135578800000)\/"}, {"DataType":349, "DefaultValue":"", "IsDirty":false, "Length":50, "ModuleDefId":-1, "PortalId":-1, "PropertyCategory":"Name", "PropertyDefinitionId":3, "PropertyName":"MiddleName", "PropertyValue":null, "Required":false, "ValidationExpression":"", "ViewOrder":5, "Visible":true, "DefaultVisibility":0, "Visibility":0, "CreatedByUserID":-1, "CreatedOnDate":"\/Date(-62135578800000)\/", "LastModifiedByUserID":-1, "LastModifiedOnDate":"\/Date(-62135578800000)\/"}, {"DataType":349, "DefaultValue":"", "IsDirty":false, "Length":50, "ModuleDefId":-1, "PortalId":-1, "PropertyCategory":"Name", "PropertyDefinitionId":4, "PropertyName":"LastName", "PropertyValue":"Account", "Required":false, "ValidationExpression":"", "ViewOrder":7, "Visible":true, "DefaultVisibility":0, "Visibility":0, "CreatedByUserID":-1, "CreatedOnDate":"\/Date(-62135578800000)\/", "LastModifiedByUserID":-1, "LastModifiedOnDate":"\/Date(-62135578800000)\/"}, {"DataType":349, "DefaultValue":"", "IsDirty":false, "Length":50, "ModuleDefId":-1, "PortalId":-1, "PropertyCategory":"Name", "PropertyDefinitionId":5, "PropertyName":"Suffix", "PropertyValue":null, "Required":false, "ValidationExpression":"", "ViewOrder":9, "Visible":true, "DefaultVisibility":0, "Visibility":0, "CreatedByUserID":-1, "CreatedOnDate":"\/Date(-62135578800000)\/", "LastModifiedByUserID":-1, "LastModifiedOnDate":"\/Date(-62135578800000)\/"}, {"DataType":349, "DefaultValue":"", "IsDirty":false, "Length":50, "ModuleDefId":-1, "PortalId":-1, "PropertyCategory":"Address", "PropertyDefinitionId":6, "PropertyName":"Unit", "PropertyValue":null, "Required":false, "ValidationExpression":"", "ViewOrder":11, "Visible":true, "DefaultVisibility":2, "Visibility":2, "CreatedByUserID":-1, "CreatedOnDate":"\/Date(-62135578800000)\/", "LastModifiedByUserID":-1, "LastModifiedOnDate":"\/Date(-62135578800000)\/"}, {"DataType":349, "DefaultValue":"", "IsDirty":false, "Length":50, "ModuleDefId":-1, "PortalId":-1, "PropertyCategory":"Address", "PropertyDefinitionId":7, "PropertyName":"Street", "PropertyValue":null, "Required":false, "ValidationExpression":"", "ViewOrder":13, "Visible":true, "DefaultVisibility":2, "Visibility":2, "CreatedByUserID":-1, "CreatedOnDate":"\/Date(-62135578800000)\/", "LastModifiedByUserID":-1, "LastModifiedOnDate":"\/Date(-62135578800000)\/"}, {"DataType":349, "DefaultValue":"", "IsDirty":false, "Length":50, "ModuleDefId":-1, "PortalId":-1, "PropertyCategory":"Address", "PropertyDefinitionId":8, "PropertyName":"City", "PropertyValue":null, "Required":false, "ValidationExpression":"", "ViewOrder":15, "Visible":true, "DefaultVisibility":2, "Visibility":2, "CreatedByUserID":-1, "CreatedOnDate":"\/Date(-62135578800000)\/", "LastModifiedByUserID":-1, "LastModifiedOnDate":"\/Date(-62135578800000)\/"}, {"DataType":357, "DefaultValue":"", "IsDirty":false, "Length":0, "ModuleDefId":-1, "PortalId":-1, "PropertyCategory":"Address", "PropertyDefinitionId":9, "PropertyName":"Region", "PropertyValue":null, "Required":false, "ValidationExpression":"", "ViewOrder":17, "Visible":true, "DefaultVisibility":2, "Visibility":2, "CreatedByUserID":-1, "CreatedOnDate":"\/Date(-62135578800000)\/", "LastModifiedByUserID":-1, "LastModifiedOnDate":"\/Date(-62135578800000)\/"}, {"DataType":356, "DefaultValue":"", "IsDirty":false, "Length":0, "ModuleDefId":-1, "PortalId":-1, "PropertyCategory":"Address", "PropertyDefinitionId":10, "PropertyName":"Country", "PropertyValue":null, "Required":false, "ValidationExpression":"", "ViewOrder":19, "Visible":true, "DefaultVisibility":2, "Visibility":2, "CreatedByUserID":-1, "CreatedOnDate":"\/Date(-62135578800000)\/", "LastModifiedByUserID":-1, "LastModifiedOnDate":"\/Date(-62135578800000)\/"}, {"DataType":349, "DefaultValue":"", "IsDirty":false, "Length":50, "ModuleDefId":-1, "PortalId":-1, "PropertyCategory":"Address", "PropertyDefinitionId":11, "PropertyName":"PostalCode", "PropertyValue":null, "Required":false, "ValidationExpression":"", "ViewOrder":21, "Visible":true, "DefaultVisibility":2, "Visibility":2, "CreatedByUserID":-1, "CreatedOnDate":"\/Date(-62135578800000)\/", "LastModifiedByUserID":-1, "LastModifiedOnDate":"\/Date(-62135578800000)\/"}, {"DataType":349, "DefaultValue":"", "IsDirty":false, "Length":50, "ModuleDefId":-1, "PortalId":-1, "PropertyCategory":"Contact Info", "PropertyDefinitionId":12, "PropertyName":"Telephone", "PropertyValue":null, "Required":false, "ValidationExpression":"", "ViewOrder":23, "Visible":true, "DefaultVisibility":2, "Visibility":2, "CreatedByUserID":-1, "CreatedOnDate":"\/Date(-62135578800000)\/", "LastModifiedByUserID":-1, "LastModifiedOnDate":"\/Date(-62135578800000)\/"}, {"DataType":349, "DefaultValue":"", "IsDirty":false, "Length":50, "ModuleDefId":-1, "PortalId":-1, "PropertyCategory":"Contact Info", "PropertyDefinitionId":13, "PropertyName":"Cell", "PropertyValue":null, "Required":false, "ValidationExpression":"", "ViewOrder":25, "Visible":true, "DefaultVisibility":2, "Visibility":2, "CreatedByUserID":-1, "CreatedOnDate":"\/Date(-62135578800000)\/", "LastModifiedByUserID":-1, "LastModifiedOnDate":"\/Date(-62135578800000)\/"}, {"DataType":349, "DefaultValue":"", "IsDirty":false, "Length":50, "ModuleDefId":-1, "PortalId":-1, "PropertyCategory":"Contact Info", "PropertyDefinitionId":14, "PropertyName":"Fax", "PropertyValue":null, "Required":false, "ValidationExpression":"", "ViewOrder":27, "Visible":true, "DefaultVisibility":2, "Visibility":2, "CreatedByUserID":-1, "CreatedOnDate":"\/Date(-62135578800000)\/", "LastModifiedByUserID":-1, "LastModifiedOnDate":"\/Date(-62135578800000)\/"}, {"DataType":349, "DefaultValue":"", "IsDirty":false, "Length":50, "ModuleDefId":-1, "PortalId":-1, "PropertyCategory":"Contact Info", "PropertyDefinitionId":15, "PropertyName":"Website", "PropertyValue":null, "Required":false, "ValidationExpression":"", "ViewOrder":29, "Visible":true, "DefaultVisibility":2, "Visibility":2, "CreatedByUserID":-1, "CreatedOnDate":"\/Date(-62135578800000)\/", "LastModifiedByUserID":-1, "LastModifiedOnDate":"\/Date(-62135578800000)\/"}, {"DataType":349, "DefaultValue":"", "IsDirty":false, "Length":50, "ModuleDefId":-1, "PortalId":-1, "PropertyCategory":"Contact Info", "PropertyDefinitionId":16, "PropertyName":"IM", "PropertyValue":null, "Required":false, "ValidationExpression":"", "ViewOrder":31, "Visible":true, "DefaultVisibility":2, "Visibility":2, "CreatedByUserID":-1, "CreatedOnDate":"\/Date(-62135578800000)\/", "LastModifiedByUserID":-1, "LastModifiedOnDate":"\/Date(-62135578800000)\/"}, {"DataType":355, "DefaultValue":"", "IsDirty":false, "Length":0, "ModuleDefId":-1, "PortalId":-1, "PropertyCategory":"Preferences", "PropertyDefinitionId":17, "PropertyName":"Biography", "PropertyValue":null, "Required":false, "ValidationExpression":"", "ViewOrder":33, "Visible":true, "DefaultVisibility":2, "Visibility":2, "CreatedByUserID":-1, "CreatedOnDate":"\/Date(-62135578800000)\/", "LastModifiedByUserID":-1, "LastModifiedOnDate":"\/Date(-62135578800000)\/"}, {"DataType":352, "DefaultValue":"", "IsDirty":false, "Length":0, "ModuleDefId":-1, "PortalId":-1, "PropertyCategory":"Preferences", "PropertyDefinitionId":18, "PropertyName":"TimeZone", "PropertyValue":"0", "Required":false, "ValidationExpression":"", "ViewOrder":35, "Visible":true, "DefaultVisibility":2, "Visibility":2, "CreatedByUserID":-1, "CreatedOnDate":"\/Date(-62135578800000)\/", "LastModifiedByUserID":-1, "LastModifiedOnDate":"\/Date(-62135578800000)\/"}, {"DataType":353, "DefaultValue":"", "IsDirty":false, "Length":0, "ModuleDefId":-1, "PortalId":-1, "PropertyCategory":"Preferences", "PropertyDefinitionId":19, "PropertyName":"PreferredLocale", "PropertyValue":"en-US", "Required":false, "ValidationExpression":"", "ViewOrder":37, "Visible":true, "DefaultVisibility":2, "Visibility":2, "CreatedByUserID":-1, "CreatedOnDate":"\/Date(-62135578800000)\/", "LastModifiedByUserID":-1, "LastModifiedOnDate":"\/Date(-62135578800000)\/"}, {"DataType":361, "DefaultValue":"", "IsDirty":false, "Length":0, "ModuleDefId":-1, "PortalId":-1, "PropertyCategory":"Preferences", "PropertyDefinitionId":20, "PropertyName":"Photo", "PropertyValue":null, "Required":false, "ValidationExpression":"", "ViewOrder":40, "Visible":true, "DefaultVisibility":0, "Visibility":0, "CreatedByUserID":-1, "CreatedOnDate":"\/Date(-62135578800000)\/", "LastModifiedByUserID":-1, "LastModifiedOnDate":"\/Date(-62135578800000)\/"}], "Region":null, "Street":null, "Telephone":null, "TimeZone":0, "Unit":null, "Website":null, "ObjectHydrated":false}, "RefreshRoles":false, "Roles":[""], "UserID":1, "Username":"host", "FullName":"SuperUser Account", "Cacheability":0, "CreatedByUserID":-1, "CreatedOnDate":"\/Date(-62135578800000)\/", "LastModifiedByUserID":-1, "LastModifiedOnDate":"\/Date(-62135578800000)\/"}

 

I think it is quite obvious which is the better choice for using with web services.  In the past I would have created a ViewModel class just for serializing, but because of the power of the JavaScriptSerializer, I can skip that step.

Just as ToJson makes it easy to save my objects as a JSON string, I can also take a string and de-serialize it into my original object.  In this case, I can’t create an anonymous object but have to de-serialize to a known type.  This is often not an issue as I rarely want to work with anonymous types directly, I use them strictly as a convenience to avoid creating viewmodels.

'Assume we recieved some JSON from a webservice
jsonstring = "{PortalID: 0, Title: 'My New Page', TabOrder: 0, ParentId: -2 }"
Dim x As TabInfo = jsonstring.FromJson(Of TabInfo)()

 

All of the usual limitations still exist – it doesn’t deal well with circular references and you can only deserialize to concrete classes with a default constructor.  Even with these limitations, this is a great feature that I find myself using more and more in my module development and I hope that now that you know about it, that you will start using it as well.

Comments

Comment Form

Only registered users may post comments.

NewsArchives


Aderson Oliveira (22)
Alec Whittington (11)
Alessandra Daniels (3)
Alex Shirley (10)
Andrew Hoefling (3)
Andrew Nurse (30)
Andy Tryba (1)
Anthony Glenwright (5)
Antonio Chagoury (28)
Ash Prasad (37)
Ben Schmidt (1)
Benjamin Hermann (25)
Benoit Sarton (9)
Beth Firebaugh (12)
Bill Walker (36)
Bob Kruger (5)
Bogdan Litescu (1)
Brian Dukes (2)
Brice Snow (1)
Bruce Chapman (20)
Bryan Andrews (1)
cathal connolly (55)
Charles Nurse (163)
Chris Hammond (213)
Chris Paterra (55)
Clint Patterson (108)
Cuong Dang (21)
Daniel Bartholomew (2)
Daniel Mettler (181)
Daniel Valadas (48)
Dave Buckner (2)
David Poindexter (12)
David Rodriguez (3)
Dennis Shiao (1)
Doug Howell (11)
Erik van Ballegoij (30)
Ernst Peter Tamminga (80)
Francisco Perez Andres (17)
Geoff Barlow (12)
George Alatrash (12)
Gifford Watkins (3)
Gilles Le Pigocher (3)
Ian Robinson (7)
Israel Martinez (17)
Jan Blomquist (2)
Jan Jonas (3)
Jaspreet Bhatia (1)
Jenni Merrifield (6)
Joe Brinkman (274)
John Mitchell (1)
Jon Henning (14)
Jonathan Sheely (4)
Jordan Coopersmith (1)
Joseph Craig (2)
Kan Ma (1)
Keivan Beigi (3)
Kelly Ford (4)
Ken Grierson (10)
Kevin Schreiner (6)
Leigh Pointer (31)
Lorraine Young (60)
Malik Khan (1)
Matt Rutledge (2)
Matthias Schlomann (16)
Mauricio Márquez (5)
Michael Doxsey (7)
Michael Tobisch (3)
Michael Washington (202)
Miguel Gatmaytan (3)
Mike Horton (19)
Mitchel Sellers (40)
Nathan Rover (3)
Navin V Nagiah (14)
Néstor Sánchez (31)
Nik Kalyani (14)
Oliver Hine (1)
Patricio F. Salinas (1)
Patrick Ryan (1)
Peter Donker (54)
Philip Beadle (135)
Philipp Becker (4)
Richard Dumas (22)
Robert J Collins (5)
Roger Selwyn (8)
Ruben Lopez (1)
Ryan Martinez (1)
Sacha Trauwaen (1)
Salar Golestanian (4)
Sanjay Mehrotra (9)
Scott McCulloch (1)
Scott Schlesier (11)
Scott Wilkinson (3)
Scott Willhite (97)
Sebastian Leupold (80)
Shaun Walker (237)
Shawn Mehaffie (17)
Stefan Cullmann (12)
Stefan Kamphuis (12)
Steve Fabian (31)
Steven Fisher (1)
Tony Henrich (3)
Torsten Weggen (3)
Tycho de Waard (4)
Vicenç Masanas (27)
Vincent Nguyen (3)
Vitaly Kozadayev (6)
Will Morgenweck (40)
Will Strohl (180)
William Severance (5)
What is Liquid Content?
Find Out
What is Liquid Content?
Find Out
What is Liquid Content?
Find Out