Search code examples
jsondelphifiremonkeydelphi-xe3

How to parse specified value from JSON object in Delphi XE3?


My JSON object looks like this:

{
   "destination_addresses" : [ "Paris, France" ],
   "origin_addresses" : [ "Amsterdam, Nederland" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "504 km",
                  "value" : 504203
               },
               "duration" : {
                  "text" : "4 uur 54 min.",
                  "value" : 17638
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

I will need the "504 km" value from distance. How can i do this?


Solution

  • You can use the DBXJSON unit, included since Delphi 2010.

    Try this sample

    uses
      DBXJSON;
    
    {$R *.fmx}
    
    Const
    StrJson=
    '{ '+
    '   "destination_addresses" : [ "Paris, France" ], '+
    '   "origin_addresses" : [ "Amsterdam, Nederland" ], '+
    '   "rows" : [  '+
    '      {      '+
    '         "elements" : [  '+
    '            {  '+
    '               "distance" : { '+
    '                  "text" : "504 km", '+
    '                  "value" : 504203   '+
    '               },  '+
    '               "duration" : {  '+
    '                  "text" : "4 uur 54 min.",  '+
    '                  "value" : 17638  '+
    '               },  '+
    '               "status" : "OK"  '+
    '            }   '+
    '         ]   '+
    '      }  '+
    '   ],   '+
    '   "status" : "OK"  '+
    '}';
    
    
    procedure TForm6.Button1Click(Sender: TObject);
    var
      LJsonObj  : TJSONObject;
      LRows, LElements, LItem : TJSONValue;
    begin
        LJsonObj    := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(StrJson),0) as TJSONObject;
      try
         LRows:=LJsonObj.Get('rows').JsonValue;
         LElements:=TJSONObject(TJSONArray(LRows).Get(0)).Get('elements').JsonValue;
         LItem :=TJSONObject(TJSONArray(LElements).Get(0)).Get('distance').JsonValue;
         ShowMessage(TJSONObject(LItem).Get('text').JsonValue.Value);
      finally
         LJsonObj.Free;
      end;
    end;