Jump to content

How to work with JSON data?


Recommended Posts

Hello,

 

my rest server is returning a JSON string. How can I parse it as JSON Object, in order I can access the values properly?

 

Here is my code snippet:

REST[W3EditBox1.Text,''].Call
    .OnDone(
      procedure(http: TW3HttpRequest)
      begin
        W3Memo1.Text := http.ResponseText;
      end)
    .onError(
      procedure(http: TW3HttpRequest)
      begin
        W3Memo1.Text := http.ResponseText;
      end)
    .Get;
Link to post
Share on other sites

The JSON data can directly be used as an object. If, for instance, your data looks like this:

{
  "Foo": "Bar"
}

you can write something like:

uses
  ECMA.JSON, W3C.Console;

[...]
var Data := JSON.Parse(http.ResponseText);

Console.Log(Data.Foo);

which would write 'Bar' to the console.

 

If you want to use type information, you can write something like this:

uses
  ECMA.JSON, W3C.Console;

type
  JFooBar = class external
    Foo: String;
  end;

[...]
var Data := JFooBar(JSON.Parse(http.ResponseText));

Console.Log(Data.Foo);

The advantage of this approach is the fact that now code completion is aware of the 'Foo' member.

 

However, keep in mind that the type cast is unsafe. If the JSON data is not the class JFooBar it will result in an unpredictable behaviour (depending on read or write access).

Link to post
Share on other sites

Brilliant answer, Christian!

 

I'm sure it's possible to find, and i know it's been discussed, but i like to point out that the "class external" approach goes both ways too. Sometimes (because of the way some name need to change from pascal to js even regardless of code obfuscation) the "class external" approach is much better than to JSON.stringify records.

Link to post
Share on other sites
  • 5 weeks later...

Is it possible to define a class for this JSON and cast to it as above? Would anyone care to write an example?

{id: 1, values: [{"name":"one", value:55, used:true}, {"name":"two", value:65, used:false}]}

Also how would a object definition look? I.e. something like:

var object := class id: Integer = 1; values ..?... end;

TIA,

 

/D

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...