Click here to Skip to main content
15,881,938 members
Articles / Web Development / HTML

Generic C# JSON Generator to Send Any Data to JavaScript

Rate me:
Please Sign up or sign in to vote.
3.62/5 (10 votes)
17 Feb 2009CPOL2 min read 83.3K   789   50   23
Generic C# JSON generator to send any managed data to JavaScript and use the same syntax to access it

Introduction

How would you like to have any data in C# (like this 3.5 sample)...

C#

... and access it from JavaScript, using the same syntax as in C#:

Javascript

"How Do They Do It?"

So there I was building a simple Ajax application using ASP.NET and it was very hard to send data from the code-behind in ASP.NET to the JavaScript code. Then I found out about JSON, which solved all the problems. The nice thing about JSON is that it is a format that browsers understand and can use to create rather complex data inside their JavaScript engines. So I wrote a recursive reflection based JSON generator that takes any managed class or struct and generates the JSON string that the browser understands.

Because this engine searches for fields in the class, there's no need to write such properties:

C#
public int Id
{
    get { return this._id; }
    set { this._id = value; }
}

You can either select all fields or mark specific fields with an attribute and only send them to the JavaScript code.

More than that, the engine can handle even the anonymous types specific to .NET 3.5 (as seen in the picture above). It seems that the anonymous types are not stored identically to the proper types in the assembly's DLL.

Using the Code

Using the code is as simple as it gets: with one line of C# code you "convert" the object to the JSON string that is sent to the client code. No need for helper classes (like type serializers).

The client code uses one eval line of code to create the DOM object.

And that's it. In .NET 3.5, you don't even have to write the class with the complex constructor to receive all the data as parameters (as it was the case in .NET 2.0).

The engine can handle primitive data types (numeric types, strings and dates), classes, structs, arrays and null fields. If you have some data in a custom collection (like generic Lists), you can use the ToArray() method to get in a form the engine understands. I've chosen to use array(s) instead of IEnumerable(s) because you might have a class that implements IEnumerable but you might not want to treat it as a collection (string is such a class).

I know the whole point of this engine is to hide the representation of the object, but here's an example of how it looks (just to have an idea).

JavaScript
{
    'date' : new Date( 2008, 1, 23, 8, 5, 52 ) ,
    'Name' : 'some string' ,
    'StringSpecial' : '\\some \' \" string' ,
    'NullString' : null ,
    'Private' : null ,
    'i' : -1 ,
    'f' : 2.3 ,
    't2' :
    {
        'd' : 3.14 ,
        'D' : 3.15 ,
        'ThisIsAStruct' :
        {
            'str' : 'string in a struct'
        }
    }
}

Now that you've been briefed, go and download the archive and try it out.

There's a Visual Studio 2005 and a Visual Studio 2008 solution. The last one includes a .NET 3.5 ASP sample to test the anonymous types I was bragging about.

If you take a look at the generator's code, you'll notice it is not even 200 lines of code long.

PS: Don't forget to set the Web project as the "start up project" inside Visual Studio.

History

  • Feb 23rd, 2008 - Initial version
  • Feb 16th, 2009 - New code version

License

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


Written By
Software Developer (Senior)
Romania Romania
Areas Of Expertise:


APIs:

.Net Framework
MFC
Win32

ActiveX (documents, controls, automation)

Graphics:

DirectX
OpenGL

Databases:

SQL Server
ADO
Odbc

Web Applications:

AJAX
ASP.Net
Web Services
ActiveX controls

Programming Languages:

C/C++
C#
Pascal
Basic
Python
Javascript
XHTML

Proud to have been part of the following team(s):

Project Viewer - Housatonic

Silent Hunter 4 - Ubisoft Romania

Personal web site (programing C++ C# ASP.NET, CV, jokes, games)

RedGoblin - boardgames store (a project i'm working on)





Comments and Discussions

 
QuestionTrouble understanding code Pin
Nadav Gur-Arieh19-Apr-16 2:24
Nadav Gur-Arieh19-Apr-16 2:24 
AnswerRe: Trouble understanding code Pin
Mihai Maerean19-Apr-16 3:26
Mihai Maerean19-Apr-16 3:26 
QuestionJsonBridge does it easier and with no headache... Pin
Evgenios Skitsanos2-Jun-12 9:51
Evgenios Skitsanos2-Jun-12 9:51 
GeneralAn idea building on this Pin
dojohansen20-Feb-09 4:01
dojohansen20-Feb-09 4:01 
GeneralNot working with an array of objet Pin
Cestbienmoi15-Feb-09 22:57
Cestbienmoi15-Feb-09 22:57 
GeneralRe: Not working with an array of objet Pin
Mihai Maerean16-Feb-09 0:14
Mihai Maerean16-Feb-09 0:14 
GeneralRe: Not working with an array of objet Pin
Mihai Maerean16-Feb-09 18:09
Mihai Maerean16-Feb-09 18:09 
GeneralRe: Not working with an array of objet Pin
Mihai Maerean17-Feb-09 18:21
Mihai Maerean17-Feb-09 18:21 
GeneralJSON to HTML Pin
aggla24-Mar-08 2:15
aggla24-Mar-08 2:15 
GeneralRe: JSON to HTML Pin
Mihai Maerean24-Mar-08 2:58
Mihai Maerean24-Mar-08 2:58 
GeneralRe: JSON to HTML Pin
aggla24-Mar-08 6:34
aggla24-Mar-08 6:34 
GeneralRe: JSON to HTML Pin
aggla24-Mar-08 9:56
aggla24-Mar-08 9:56 
GeneralWhy? Maybe an Answer Pin
Dewey23-Feb-08 17:42
Dewey23-Feb-08 17:42 
QuestionWhy? Pin
stevekain23-Feb-08 6:17
stevekain23-Feb-08 6:17 
AnswerRe: Why? Pin
Steven Berkovitz23-Feb-08 6:35
Steven Berkovitz23-Feb-08 6:35 
I think you mean the JSON serializer (JavaScriptSerializer) that is included in the System.Web.Script.Serialization namespace.

-Steven

AnswerRe: Why? Pin
Mihai Maerean23-Feb-08 7:54
Mihai Maerean23-Feb-08 7:54 
GeneralRe: Why? Pin
Cestbienmoi15-Feb-09 22:55
Cestbienmoi15-Feb-09 22:55 
GeneralRe: Why? Pin
dojohansen20-Feb-09 4:10
dojohansen20-Feb-09 4:10 
AnswerRe: Why? Pin
Mihai Maerean23-Feb-08 8:11
Mihai Maerean23-Feb-08 8:11 
GeneralRe: Why? Pin
CitizenDC19-Mar-08 0:04
CitizenDC19-Mar-08 0:04 
GeneralRe: Why? Pin
Mihai Maerean19-Mar-08 0:09
Mihai Maerean19-Mar-08 0:09 
AnswerRe: Why? Pin
Jamie Nordmeyer18-Feb-09 2:39
Jamie Nordmeyer18-Feb-09 2:39 
AnswerRe: Why? Pin
dojohansen20-Feb-09 4:13
dojohansen20-Feb-09 4:13 

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.