0
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.

3
  • 1
    Records are not classes. Make your tbet type a class, too, so it also becomes an object instead of an array for JSON. Commented Apr 30, 2022 at 18:12
  • Yes i need to keep it as type record as said above. If there is no solution i will change it to class. Commented Apr 30, 2022 at 19:10
  • 2
    as already told you record needs to be a class but this way is also terrible wrong you need to learn to create json objects and arrays with Tjsonobject.create and tjsonarray..create and all your problems will gone. Commented Apr 30, 2022 at 19:46

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.