Stream JSON to TObject

I see that in V2.4.5.0 a new class is introduced to Stream any TObject in JSON and vice versa

An example to convert TObject in JSON is in the blog (TMS Software | Blog)

But I can't see example for the conversion from a JSON (received by TXDataClientResponse) to a TObject. Is it possible?

Rgds,

I don't see why it wouldn't be possible as XData communication is just via JSON, in the end, pure JS objects.

For a simple Object, it's easy, but if this object contains TLists, it doesn't work.

If my webservice returns a TClient :

  TAddress = class
    Street: string;
    number: integer;
  end;

  TClient = class
    firstName: string;
    lastName: string;
    AddressList: TList<TAddress>;
  end;

which gives in JSON :

{
    "$id": 1,
    "firstName": "Neil",
    "lastName": "Armstrong",
    "AddressList": [
        {
            "$id": 2,
            "Street": "Mainstreet",
            "number": 1
        },
        {
            "$id": 3,
            "Street": "First avenue",
            "number": 2
        }
    ]
}

I can get firstName & lastName, but not the Addresslist :

procedure OnResult(Response: TXDataClientResponse);
var
	MyClient: TClient;
	JSObj: TJSObject;
begin
	JsObj:=Response.ResultAsObject;
	MyClient := TClient.Create;
	MyClient.AddressList:=TList.create;
	MyClient := TClient(JSObj);
	Showmessage(MyClient.firstName); // OK
	Showmessage(MyClient.AddressList[0].Street) // BUG
end;

Is there another way to convert a TJSObject to a TObject?

You can't simply cast a TJSObject to an object declared as a Pascal object:

It doesn't work, because internally they have different structures.
You should declare your TClient class as external and treat lists as arrays:

  TClient = class external name 'Object'
    firstName: string;
    lastName: string;
    AddressList: TArray<TAddress>;
  end;

Reference:

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.