'How can I parse a nested TJSONObject in Delphi?
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?
Solution 1:[1]
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;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | AmigoJack |
