Example code : Parsing a JSON object to Variant 1
|
function JSON2Variant(AResponse: string): Variant;
begin
asm
@Result=JSON.parse(@AResponse);
end;
end;
procedure TForm1.W3Button2Click(Sender: TObject);
var
mJSON: String;
mData: Variant;
Begin
mJSON := '{"RowID":10,"FirstName":"abc","LastName":"def","YearOfBirth":20,"YearOfDeath":30,'+
'"Sexe":1,"Simple":{"F":"","G":[],"H":{"H1":0,"H2":"","H3":{"H3a":false,"H3b":null}},"I":"","J":['+
'{"J1":1,"J2":"","J3":"reLast"}]}}';
mData:=JSON2Variant(mJSON);
WriteLn(mData);
{ Accessing the elements of the JSON }
WriteLn('mData.firstName = ' + mData.FirstName);
WriteLn('mData.lastName = ' + mData.LastName);
WriteLn('mData.YearOfBirth = ' + mData.YearOfBirth);
end;
|
|
Result is:
{
"RowID" : 10,
"FirstName" : "abc",
"LastName" : "def",
"YearOfBirth" : 20,
"YearOfDeath" : 30,
"Sexe" : 1,
"Simple" : {
"F" : "",
"G" : [],
"H" : {
"H1" : 0,
"H2" : "",
"H3" : {
"H3a" : false,
"H3b" : null
}
},
"I" : "",
"J" : [{
"J1" : 1,
"J2" : "",
"J3" : "reLast"
}
]
}
}
mData.firstName = abc
mData.lastName = def
mData.YearOfBirth = 20
Example code : Parsing a JSON object to Variant 2
|
type
JMyObject = class external "object"
public
function JSON2Variant(AResponse: string): Variant;
end;
function JSON2Variant(AResponse: string): Variant;
begin
asm
@Result=JSON.parse(@AResponse);
end;
end;
procedure TForm1.W3Button2Click(Sender: TObject);
var
mJSON: String;
mData: Variant;
LObject: JMyObject;
Begin
mJSON := '{"RowID":10,"FirstName":"abc","LastName":"def","YearOfBirth":20,"YearOfDeath":30,'+
'"Sexe":1,"Simple":{"F":"","G":[],"H":{"H1":0,"H2":"","H3":{"H3a":false,"H3b":null}},"I":"","J":['+
'{"J1":1,"J2":"","J3":"reLast"}]}}';
LObject:=JMyObject(JSON2Variant(mJSON));
{ Just checking the variant content }
WriteLn(LObject);
{ Parsin the JSON into a variant }
mData := LObject; //mData:=JSON2Variant(mJSON);
{ Accessing the elements of the JSON }
WriteLn('mData.firstName = ' + mData.FirstName);
WriteLn('mData.lastName = ' + mData.LastName);
WriteLn('mData.YearOfBirth = ' + mData.YearOfBirth);
end;
|
|
Result is:
{
"RowID" : 10,
"FirstName" : "abc",
"LastName" : "def",
"YearOfBirth" : 20,
"YearOfDeath" : 30,
"Sexe" : 1,
"Simple" : {
"F" : "",
"G" : [],
"H" : {
"H1" : 0,
"H2" : "",
"H3" : {
"H3a" : false,
"H3b" : null
}
},
"I" : "",
"J" : [{
"J1" : 1,
"J2" : "",
"J3" : "reLast"
}
]
}
}
mData.firstName = abc
mData.lastName = def
mData.YearOfBirth = 20
|