Question

json support is one of the new features of delphi 2009 and delphi 2010. I want to know if it's there any simple function to marshalling/unmarshalling directly between string and object like in superobject library.

Example:

MyKnownObject := FromJSON('{name:"francis", surname:"lee"}');
Was it helpful?

Solution

Unserialize a string directly to a TJSONObject

var
  ConvertFrom: String;
  JSON: TJSONObject;
  StringBytes: TBytes;
  I: Integer;
begin
  ConvertFrom := '{"name":"somebody on SO","age":"123"}';
  StringBytes := TEncoding.ASCII.GetBytes(ConvertFrom);
  JSON := TJSONObject.Create;
  try
    JSON.Parse(StringBytes, 0);
    Assert(JSON.ToString = ConvertFrom, 'Conversion test');
    Memo1.Lines.Add(JSON.ToString);

    for I := 0 to JSON.Size - 1 do
      Memo1.Lines.Add(JSON.Get(I).JsonString.Value + 
         ' : ' + JSON.Get(I).JsonValue.Value);

  finally
    JSON.Free;
  end;
end;

OTHER TIPS

See here. Bellow is snipped the interesting part:

procedure TForm13.Button4Click(Sender: TObject);
var
  LContact: TContact;
  oMarshaller: TJSONMarshall;
  crtVal: TJSONValue;
begin
  LContact:=TContact.Create; //our custom class
  LContact.Name:='wings-of-wind.com';
  LContact.Age:=20; //fill with some data
  oMarshaller:=TJSONMarshal.Create(TJSONConverter.Create); //our engine
  try
    crtVal:=oMarshaller.Marshal(LContact); //serialize to JSON
    Memo1.Text:=crtVal.ToString; //display
  finally //cleanup
    FreeAndNil(LContact);
    FreeAndNil(oMarshaller);
  end;
end;

Also you can see here a more complicated example by Adrian Andrei (the DataSnap architect) as well as an example of custom marshaling here.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top