My Delphi application calls a REST API, which produces the following JSON:
{
"status": "success",
"message": "More details",
"data": {
"filestring": "long string with data",
"correct": [
{
"record": "Lorem ipsum",
"code": 0,
"errors": []
}
],
"incorrect": [
{
"record": "Lorem ipsum",
"code": 2,
"errors": [
"First error",
"Second error"
]
}
],
}
}
I now want to work with the data, but I am unable to receive the information stored in the data
section. Currently I am trying to receive the data like below:
var
vResponse : TJSONObject;
vData : TJSONObject;
begin
// .. do other stuff ..
vResponse := // call to REST API (Returns a valid TJSONObject I've wrote it into a file)
vData := vResponse.get('data'); // throws error
end;
But this leads to the following error:
Incompatible Types: TJSONObject and TJSONPair
Does anybody know how I can achieve this?
CodePudding user response:
Incompatible Types: TJSONObject and TJSONPair
The error message is self explaining: vData
is declared as TJSONObject
, which means that the return type of the Get
function is TJSONPair
.
To fix such errors you need to change the declaration of the result variable. In this case that would mean declaring vData
as TJSONPair
.
However, if you are not interested in getting a pair, but instead TJSONObject
, you need to use other ways to retrieve it. For instance the Values
property. Because Values
returns TJSONValue
you need to typecast it to TJSONObject
if you know that the value is an object.
vData := vResponse.Values['data'] as TJSONObject;
CodePudding user response:
TJSONObject.Get()
returns a TJSONPair
, not a TJSONObject
. You will have to either:
use the
TJSONPair.JsonValue
property:var vResponse : TJSONObject; vData : TJSONObject; begin // .. do other stuff .. vResponse := // call to REST API (Returns a valid TJSONObject I've wrote it into a file) vData := vResponse.Get('data').JsonValue as TJSONObject; end;
use the
TJSONObject.GetValue()
method, which returns just theJsonValue
of the foundTJSONPair
:var vResponse : TJSONObject; vData : TJSONObject; begin // .. do other stuff .. vResponse := // call to REST API (Returns a valid TJSONObject I've wrote it into a file) vData := vResponse.GetValue('data') as TJSONObject; end;