Steven Chesser
Steven Chesser

Reputation: 11

Get xsuperobject to parse unnamed array to tobject structure

I am using Delphi 10.1 Berlin Update 2, and am trying to use XSuperObject / XSuperJSON to take a JSON response from a 3rd party provider and parse it into an object structure.

Here is the JSON:

[ 
  {
    "yardNumber": 10,
    "links": [
      {
        "rel": "yardSaleList",
        "href": "<url address>"
      }
    ],
    "yardName": "Yard A",
    "auctionDate": "1/25/17"
  },
  {
    "yardNumber": 10,
    "links": [
      {
        "rel": "yardSaleList",
        "href": "<url>"
      }
    ],
    "yardName": "Yard B",
    "auctionDate": "1/25/17"
  }
] 

My code is something like this:

TLinkItem = class
public
  [alias('rel')]
  rel: String;
  [alias('href')]
  href: string;
end;    

TPartItem = class
public
  [alias('yardNumber')]
  YardNumber: integer;
  [alias('links')]
  Links: TObjectList<TLinkItem>;
  [alias('yardName')]
  YardName: string;
  [alias('auctionDate')]
  AuctionDate: String; 
  destructor destroy; override;
end;

TPartItems = class  /// not used because this is an unnamed JSON array
public
  [alias('ItemData')] 
  ItemData : TObjectList<TPartItem>;     
end;

...

destructor TPartItems.destroy;
begin
  freeandnil(Links);
  inherited;
end;

If it were a named array, I could use the above object to refer to the name of the array:

myData := TPartItems.FromJSON(jsonString); 
showmssage(myData.ItemData.count.toString);

But because this is an unnamed array, I can't do that.

I'm hoping I have just missing some kind of detail here that I could not find. Until now, this has worked pretty well with other data suppliers, but I have never run across an unnamed JSON array like this.

Upvotes: 1

Views: 595

Answers (3)

Since I can´t comment, I´ll complement @AhmetSinav

answer:

res := idHttp.get('api/ajustes/127');
objReg := SO(res);
for i := 0 to objReg.A['registros'].Length-1 do
begin
   ShowMessage(objReg.A['registros'].o[i].S['id']);
   //....
end;

Upvotes: 0

AhmetSinav
AhmetSinav

Reputation: 55

Basicaly you can do addition to @Remy Lebeau

sResponse := '{"arr":'+sResponse+'}'; 
XSO := SO(sResponse);

for I := 0 to XSO.A['arr'].Length-1 do
begin
   XSO.A['arr'].o[i].S['yardNumber'];
   //....
end;

Upvotes: 0

Remy Lebeau
Remy Lebeau

Reputation: 598134

I looked at XSuperObject's source and do not see anything that would allow the JSON you have shown to stream an unnamed array into TPartItems directly. So, I would suggest simply wrapping the JSON array inside of a JSON object that gives the array a name, eg:

myData := TPartItems.FromJSON('{ItemData: ' + jsonString + '}');

Upvotes: 3

Related Questions