如何解析Delphi XE3中JSON对象的指定值? [英] How to parse specified value from JSON object in Delphi XE3?

查看:258
本文介绍了如何解析Delphi XE3中JSON对象的指定值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的JSON对象如下所示:

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"
}

将需要距离504公里的值。我该怎么做?

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

推荐答案

您可以使用 DBXJSON 单元。

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

这个样本

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;

这篇关于如何解析Delphi XE3中JSON对象的指定值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆