0

I'm new to Delphi and I learn it at the moment. I have this peace of code. It works very well.

procedure TForm2.Button1Click(Sender: TObject);
var
  jValue : TJSONValue;
  JsonArray: TJSONArray;
begin

  RESTRequest1.Execute;
  jValue := RESTResponse1.JSONValue;

  // Ist this the right way? --> JsonArray := TJSonObject.ParseJSONValue(jValue.ToString) as TJSONArray;

  MemoContent.Lines.Add('Zitat des Tages:');
  MemoContent.Lines.Add(jValue.ToString);

end;

The output is the following JSON String:

Zitat des Tages:\n
{"951":{"zitat":"\nWo ein Wille ist, ist auch ein Holzweg.\n\n","autor":"André Brie"},"timestamp":"2020 09 03 19:21:36"}

Now, I want to parse the JSON Object to write zitat, autor to my memo. But I don't know to do that. I've read a lot, but I don't understand to get my string into an array and then to parse it to the elements.

Any tipps or some help from you profies?

Thanks for help.

1
  • 2
    The TRESTResponse.JSONValue is already parsed for you. You do not need to convert it to a string just to re-parse it yourself. Change this: JsonArray := TJSonObject.ParseJSONValue(jValue.ToString) as TJSONArray; to this: JsonArray := jValue as TJSONArray; Commented Sep 3, 2020 at 19:40

1 Answer 1

2

This code will probably do the parsing you need:

    uses System.JSON;
    
    procedure TForm1.Button1Click(Sender: TObject);
        JSonData   : String;
        JSonObject : TJSonObject;
        JSonValue  : TJSonValue;
        Zitat      : String;
    begin
        JSonData   := '{"951":{"zitat":"\nWo ein Wille ist, ist auch ein Holzweg.\n\n","autor":"André Brie"},"timestamp":"2020 09 03 19:21:36"}';
        JSonObject := TJSonObject.ParseJSONValue(JSonData) as TJSonObject;
        try
            JSonValue := JSonObject.Get('951').JSONValue;
            Zitat     := JSonValue.GetValue<string>('zitat');
        finally
            JSonObject.Free;
        end;
        ShowMessage(Zitat);
    end;

You should add more testing to handle cases where JSON data is malformed or doesn't contain the required data.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.