I always enjoy reading ScottGu's Blog. A recent post about Json and extension methods grabbed my attention, since I've been looking into Json. I'm using Delphi, so I wondered how I could do something similar, and then it occurred to me that Class Helpers would enable me to do that.
What follows is the Delphi for dotnet version
TJsonHelper=class Helper for TObject
public
function ToJson():string;overload;
function ToJson(recursionDepth:integer):string;overload;
end;
implementation
uses
System.Web.Script.Serialization;
{ TJsonHelper }
function TJsonHelper.ToJson: string;
var
serializer: JavaScriptSerializer;
begin
serializer:=JavaScriptSerializer.Create;
result:=serializer.Serialize(self);
end;
function TJsonHelper.ToJson(recursionDepth:integer): string;
var
serializer: JavaScriptSerializer;
begin
serializer:=JavaScriptSerializer.Create;
serializer.RecursionLimit:=recursionDepth;
result:=serializer.Serialize(self);
end;
Pretty cool.
You need to add a reference to the System.Web.Extensions assembly to your project. Once you add the unit reference for the class above, you can now do
someOne:=Person.Create;
someOne.Firstname:='John';
someOne.Sirname:='Smith';
people.Add(someOne);
Context.Response.Write(people.ToJson);
Person is an object I created with a couple of properties and people is declared as List<Person>