Search Flex Components Free

Custom Search

December 7, 2007

Flex + JSON + .Net Sample Application / Tutorial

Don't have enough time to wait for Adobe to release .NET Remoting for Flex? Not quite ready to dive into Flourine? Not able to purchase or install webOrb.NET on your server? Dreading working with XML and WebServices? Me Too, Me Too, Me Too, Me Too. Luckily, I've found something that seems to have made my life a little easier for the time being. JSON - as originally explained by Mike Chambers here. JSON for Actionscript 3.0, a jewel written by Darron Schall for Adobe, in the corelib released by Adobe and JSON.net for .NET.

JSON - pronounced Jason - allows you to serialize and deserialize data.

Broken down: You can send a bunch of different data types from .NET <-> Flex including Arrays and Objects and Arrays of Objects. Where I see room for improvement would be after getting a generic object, being able to automatically convert that to a ValueObject (TransferObject) on both the client and server side. Until that happens, I'll just take care of it manually - unless someone has a better recommendation.

On With The Show:

First you will need the following to follow this tutorial: Visual Studio 2005, Adobe Flex Builder 2.0, JSON.net

Open Visual Studio and Create a New Web Service: File -> New -> Website -> ASP.NET Web Service.

A file Service.asmx will be created and in the folder "App_Code" Sective.cs will be created. Open Service.cs. Enter the following code.

PLAIN TEXTC#:
using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using Newtonsoft.Json;

public class Employee
{
public int id = 0;
public string firstName = "";
public string lastName = "";
}

public class Service : System.Web.Services.WebService
{
public Service () {
}

[WebMethod]
public string GetEmployee() {
Employee e = new Employee();
e.id = 12345;
e.firstName = "Sam";
e.lastName = "Shrefler";

string output = JavaScriptConvert.SerializeObject(e);

return output;
}
}

Next, you'll need to copy "Newtonsoft.Json.dll" and "Newtonsoft.Json.XML" into your App_Code directory. Next, right-click the Project and go to "Add Reference". Select Browse then Find "Newtonsoft.Json.dll" and hit OK. A Bin directory should be created containing the "Newtonsoft.Json.dll" and "Newtonsoft.Json.XML" in your project. Right click on Service.asmx and go to "View in Browser". A Service Description should come up. Click "GetEmployee" then click "Invoke". If all is working properly, you should see the following output:

Related Flex Tutorials