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.
[csharp]
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;
}
}
[/csharp]
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:
[xml]
[/xml]
Great! Your Webservice is ready to go. Next we’ll move to the client-side: Flex!
Create a new Project. In the main mxml file, add the following code:
[as]
import mx.rpc.events.ResultEvent;
import mx.collections.ArrayCollection;
import com.adobe.serialization.json.JSON;
private function onJSONLoad(event:ResultEvent):void
{
//get the raw JSON data and cast to String
var rawData:String = String(event.result);
//De-serialize the object
var employee:Object = JSON.decode(rawData);
//Add the Object to an Array
var arr:Array = new Array();
arr.push(employee);
//create a new ArrayCollection passing the de-serialized Object Array
//ArrayCollections work better as DataProviders, as they can
//be watched for changes.
var dp:ArrayCollection = new ArrayCollection(arr);
//pass the ArrayCollection to the DataGrid as its dataProvider.
grid.dataProvider = dp;
}
]]>
[/as]
Compile and Build the application. You should see the data grid populated with one record straight from ASP.NET. Future enhancements I’d like to make to this application will be to clean the source, implement cairngorm in the flex code, and find a way to automatically transfer from generic objects to value objects in both Flex and .NET.
I hope this helps and any feedback is appreciated!
Â

“Not able to purchase or install webOrb.NET on your server?” - Wonder what kind of problem you ran into with the installation? Btw, the functionality you described does not require a purchase of WebORB.
Cheers
Mark:
I meant for people who dont’ have server access to install WebOrb. Please educate me on how I can obtain the functionality I’ve described without purchasing WebOrb.
Thank You
Sam
You can use the standard edition of the product which is available free of charge. You’d need to use AMF0 remoting to invoke the .NET service though. All the AMF0 support is available in Standard. However, native Flex integration (AMF3) is in the Professional Edition.
[...] Another alternative suggested on the group was to use JSON. It turns out that there is a Flex JSON implementation and a .NET one, neither of which I had heard of before. Sam Shrefler explains… Thanks Sam that looks just the ticket. [...]
How bout sending to asp? I don’t think I see that part here… any gotcha’s?
rd:
To be honest, i haven’t been using JSON. I went from JSON to WebOrb, and now to Fluorine, which so far, i’m totally thrilled.
Best of luck
Sam
I am trying to use fluorine in my project and i’ve been scratching my head for 3 days to figure out why
a custom type object can be passed flex–>.net but not
.net–>flex.
When I try to convert the returned object into my custom type by doing CustomType(returnedObject), I get an error on the flex side saying that object@…
cannot be converted into my custom type.
Any idea?
Oh and also, when returning an object(.net–>flex) whose properties haven’t been set, a null is returned..weird.
Thank you in advance;)
I dnot seem to have the com.adobe.serialization.json import - It’s not in my framework libs directory - Any idea where I can get it, and more importantly, why is it not included in the default install?
I am having a problem. I am getting this error in the flex IDE.
2 1120: Access of undefined property JSON.
Help on this will be appreciated.
@Sahil: You need to use the corelib provided by adobe on http://code.google.com/p/as3corelib/
@Thomas You need to add the corelib.swc to your library path (in your project properties and then import com.adobe.serialization.json.JSON
@Everyone: I just found out that the Newtonsoft implemetation does not work if you use primitive types. Only for custom objects and collections (includes arrays , lists etc.). Is this alright? Shouldn’t I be able to send primitive types too across the wire without first wrapping in a custom structure?
The other problem I am facing is passing DateTime type from .Net to flex. On the flex side while decoding a get an error that “null was expected but found new instead.”
Any ideas how to work around this?
Is it possible without Webservices to get data from Flex to .net application?
Did anyone manage to pass date times from FLEX -> .NET?
I fail to see the point here. You’re wrapping a JSON message inside a SOAP message, that’s almost double the overhead. Also the JSON parser is implemented in AS code, while the SOAP client and XML parser is native Flash Player code, which should be much faster. Above all, if you’re gonna use mx:WebService, why not go with full SOAP? What’s the advantage of using JSON in this manner?
I suggest that people interested in this look for the AJAX.ASP.NET extensions that make .NET WebServices expose JSON, and using a plain mx:HTTPRequest and feeding it’s response into the JSON decoder. That would make more sense, and would look very much like Ajax…
Hi,
Here I’ve seen the sample for sending bulk datas from .Net -> Flex. Can you give the sample for Flex -> .Net. I want to send some bulk datas from Flex -> .Net vice versa. Also Can you tell me about serialization.
Thanks,
PradeepKumar D.
I struggled with the dates aspect of .Net and Flex integration and ended up with a pretty peculiar work around.
I explicitly build the dates in a structure that Flext understands on the MSSQL server side. The WS recieves and processes this information as string. Flex accepts the data, then converts it from String to Date.
So long story short
Date -> string -> string -> Date
How to insert the flexcontrol values into database(SQLSERVER 2005)
Also, I don’t think JavaScriptConvert.SerializeObject works with dates. That conversion was designed with javascript in mind, not Flex, so I don’t think the JSON is formatted in a way that Flex can handle date types. Still investigating, though.
Hi,
I am using Flex application with .Net. I want to open an aspx page (modal dialog box) on click of the button which is in flex application. How can i acheive this?
Thanks in advance
Hi….I am very interesting with the ability to use .NET and Flex 3 together. Where can I obtain the “Newtonsoft.Json.dll” and “Newtonsoft.Json.XML” you mentioned?
Thanks for your help.
I got your tutorial to work. My test data for the webservice
{”id”:12345,”firstName”:”Charlie”,”lastName”:”Nguyen”,”address”:”2802 N. Ave.”}
when I am trying to put the employee info in a loop it renders this:
{”id”:12346,”firstName”:”Jean”,”lastName”:”Gray”,”address”:”NYC, NC”}
{”id”:12347,”firstName”:”Scott”,”lastName”:”Summers”,”address”:”NYC, NC”}
and when the datagrid populars the data….it only shows scott summers and not 2 separate rows.
does the webservices need to populate it like this? If so, how can I do that?
{”id”:12347,”firstName”:”Scott”,”lastName”:”Summers”,”address”:”NYC, NC”}
{”id”:12346,”firstName”:”Jean”,”lastName”:”Gray”,”address”:”NYC, NC”}
Thanks a lot!!
Thanks. This a good start and I plan to look at your other articles that deal with the whole Flash/Flex working with .net.
Hi,
i have the following error while using JSON even after i have added in to project buildpath libraries in FLEX Builder 2 ,
1120: Access of undefined property JSON.
Rohit,
any workaround for the date issues from .NET into Flex JSON. I change the code to encode dates as new Date(12873548273548) but not sure what to do for the decode side of things.
Ken
I was going through the whole conversations. I was just wondering why JSON serialization in the SOAP message as Ricardo has exactly pointed out correctly. Besides all, Flex can directly work with .NET Web Services itself.
I have a differrent idea what if we could directly talk with ADO.NET Data Service with REST? Anybody tried that? What about security implementation? Please suggest…
Hi,
can you tell me how to send a arraycollection from flex and handle it in .NET using JSON
Hi Vinitha
You dont need to open a aspx dialog box in Flex. The file open dialig box is available in the Flex too
Hi ,
I have a method
public static string Serialize(this object dataToSerialize)
{
var jsonSerializer = new JsonSerializer();
var stringWriter = new StringWriter();
var writer = new JsonTextWriter(stringWriter) { Formatting = Formatting.Indented };
jsonSerializer.Converters.Add(new UtcDateConverter());
jsonSerializer.Serialize(writer, dataToSerialize);
return stringWriter.ToString();
}
if a photoFile which a property of object is 172 kb, then after serialization it becomes very large, which takes too much time to upload to server. Is there any way, I can optimize serialization in terms of data size.
Thanks,
Veena