Building a ToJson() Extension Method using Delphi 2007

by john 10/3/2007 10:18:00 PM

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>

 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags:

ASP.Net 2.0 | Delphi

Related posts

Comments

Comments are closed

Powered by BlogEngine.NET 1.3.0.0
Theme by Mads Kristensen

About the author

Name of author John Moshakis
I'm a software developer living in Toronto..

E-mail me Send mail

Calendar

<<  December 2014  >>
MoTuWeThFrSaSu
24252627282930
1234567
891011121314
15161718192021
22232425262728
2930311234

View posts in large calendar

Pages

    Recent posts

    Recent comments

    Authors

    Tags

    Don't show

      Disclaimer

      The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

      © Copyright 2014

      Sign in