views:

435

answers:

3

Hello Folks,

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"}');
A: 

I tried this but it didn't work: ...

var

 j:TJSONObject;

begin

 j := TJSONObject.Create;
 j.ParseJSONValue( BytesOf('{name:"francis", surname:"lee"}'),0);
...

end;
Warren P
Also, have you looked over here:http://www.progdigy.com/?page_id=6
Warren P
this is the link to superobject library which is trully powerfull. But I want to know if I can do this directly with the VCL.
Francis Lee
+1  A: 

See here. Bellow is snipped the interesting part:

procedure TForm13.Button4Click(Sender: TObject);
02  var
03    LContact: TContact;
04    oMarshaller: TJSONMarshall;
05    crtVal: TJSONValue;
06  begin
07    LContact:=TContact.Create; //our custom class
08    LContact.Name:='wings-of-wind.com';
09    LContact.Age:=20; //fill with some data
10    oMarshaller:=TJSONMarshal.Create(TJSONConverter.Create); //our engine
11    try
12      crtVal:=oMarshaller.Marshal(LContact); //serialize to JSON
13      Memo1.Text:=crtVal.ToString; //display
14    finally //cleanup
15      FreeAndNil(LContact);
16      FreeAndNil(oMarshaller);
17    end;
18  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.

And what about unmarshalling?
Francis Lee
@Francis unmarshalling is discussed in the linked articles.
skamradt
@skamradt examples unmarshalls from TJsonValue, not from string.
Francis Lee
+1  A: 

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;
Juraj Blahunka