Reputation: 41
type
tbet = record
fteam1: string;
fteam2: string;
fskor: string
end;
type
tdeltio = class
private
fusername: string;
fpassword: string;
fbet: array of tbet;
fprice: currency;
end;
deltio := Tdeltio.Create;
deltio.fusername := 'Vanias';
deltio.fpassword := '12345';
deltio.fprice := '70';
SetLength(deltio.fbet, 1);
deltio.fbet[0].fteam1 := 'Team1';
deltio.fbet[0].fteam2 := 'Team2';
deltio.fbet[0].fskor := '1-1';
var json := Tjson.ObjectToJsonString(deltio);
json
result is like that:
{"username":"Vanias","password":"12345","bet":[["Team1","Team2","1-1"]],"price":70}
My problem is I expected something like this instead:
{"username":"Vanias","password":"12345","bet":[{"Team1":"Team1","Team2":"Team2","skor":"1-1"}],"price":70}
Why does the record type not have the property names? Ι know I can use a class for the tbet
type, but I prefer a record type.
Upvotes: 0
Views: 1692
Reputation: 703
More recent versions of Delphi (not sure when it was introduced) introduces TJsonSerializer in System.Json.Serializers that saves the Json in the format the OP describe above.
uses
System.Json.Serializers;
var
origBet,newBet:TBet;
begin
var serializer:=TJsonSerializer.Create;
var str:=serializer.Serialize(origBet);
var newBet:=serializer.DeSerialize<TBet>(str);
serializer.Free;
end
Upvotes: 0
Reputation: 595320
TJson
is hard-coded to marshal a record
type as a JSON array, not as a JSON object. This is by design, and you cannot change this behavior.
So, either use a class
type instead, or else don't use ObjectToJsonString()
at all. There are plenty of alternative approaches available to get the output you want, such as by using TJSONObject
and TJSONArray
directly, or by using a 3rd party JSON library that supports record
types as JSON objects.
Upvotes: 4