问题
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.
回答1:
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 + '}');
回答2:
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;
来源:https://stackoverflow.com/questions/41557618/get-xsuperobject-to-parse-unnamed-array-to-tobject-structure