Jump to content
DavidOne

Reading REST response JSON pair

Recommended Posts

Hello,

I am developing on Delphi 11.1.

I would like to read a JSON pair REST response received by TRESTResponse object.

The response has the following format: {"OrderNo", "W00001987"}.

In my first attempt to get the OrderNo value I used this code:

 

 OrderNoRESTResp.RootElement := 'OrderNo';
    var S: string := OrderNoRESTResp.Content;
    Result := OrderNoRESTResp.JSONValue.ToString;

 

But in the result were reported the double quotes aoround the order no.

After I try with the following code and I get the right order no without double quotes:


      Jsv: TJSONValue := OrderNoRESTResp.JSONValue;
      try var Jso: TJSONObject := Jsv as TJSONObject;
      for var JPair: TJSONPair in Jso do Result := JPair.JSONValue.Value;
 

Is the above code the correct one and the best way to retrieve a single Json pair returned from the TRESTResponse ?

 

Thank you,

Davide

 

Share this post


Link to post
7 hours ago, DavidOne said:

OrderNoRESTResp.RootElement := 'OrderNo';

Result := OrderNoRESTResp.JSONValue.ToString; 

Use the Value() method instead of the ToString() method:

OrderNoRESTResp.RootElement := 'OrderNo';
Result := OrderNoRESTResp.JSONValue.Value;

In this example, the JSONValue will point at a TJSONString, which overrides Value() to return the plain content.

7 hours ago, DavidOne said:

But in the result were reported the double quotes aoround the order no.

As it should be, since ToString() is meant for obtaining JSON formatted data, not plain data.

7 hours ago, DavidOne said:

After I try with the following code and I get the right order no without double quotes:

You don't need to resort to accessing the JSON pairs directly in this case.

 

Besides, if you are setting the RootElement to 'OrderNo', that code won't work, because the JSONValue will be pointing at a TJSONString not a TJSONObject, so the 'as' operator would raise an exception.

 

But, if you are leaving the RootElement blank, then the JSONValue will be pointing at the whole TJSONObject, yes, and then you are effectively just accessing TJSONObject(JSONValue).Get('OrderNo').Value() in a round-about way.  But, notice that you are using Value() instead of ToString() to read the string data?  Same solution as above, ultimately.

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×