2017年9月7日 星期四

JSON

unit Unit1;

interface

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
  DBXJSON;

type
  TForm1 = class(TForm)
    Button1: TButton;
    Memo1: TMemo;
    Button2: TButton;
    Button3: TButton;
    procedure Button1Click(Sender: TObject);
    procedure Button2Click(Sender: TObject);
    procedure Button3Click(Sender: TObject);
  private
    { Private declarations }
    function fn_JSON_ParseValue(AJSON,  APairName:String):String;  //JSON 取值
  public
    { Public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}



function TForm1.fn_JSON_ParseValue(AJSON,  APairName:String):String;
var objJson:TJSONObject;
  jsPair: TJSONPair;
  jsName, jsValue: TJsonValue;
  sName, sValue:String;
begin
  //JSON 取值
  Result := '';
  objJson := TJSONObject.Create;
  objJson.Parse(BytesOf(AJSON), 0);

  jsPair := TJSONPair.Create;
  jsPair := objJson.Get(APairName);

  if Assigned(jsPair) then
  begin
    jsName := jsPair.JsonString;
    jsValue := jsPair.JsonValue;
    sName := jsName.ToString;   //Ex: "Name"
    sName := jsName.Value;      //Ex: "Name" -> Name
    sValue := jsValue.ToString; //Ex: "2"
    //sValue := jsvalue.Value;    //Ex: "2" -> 2
    Result := sValue;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var sJson, sValue:String;
begin
  sJson := '{"A":"1","B":"2"}';

  sValue := fn_JSON_ParseValue(sJson, 'B');

  memo1.Lines.Add(svalue);
end;

procedure TForm1.Button2Click(Sender: TObject);
var s, sValue:String;
begin
  s :=
    '{' +
    '    "name": {'+
    '        "A JSON Object": {' +
    '          "id": "1"' +
    '        },' +
    '        "Another JSON Object": {' +
    '          "id": "2"' +
    '        }' +
    '    },' +
    '    "totalobjects": "2"' +
    '}';
  sValue := fn_JSON_ParseValue(s, 'name');
  sValue := fn_JSON_ParseValue(sValue, 'A JSON Object');
  sValue := fn_JSON_ParseValue(sValue, 'id');
  memo1.Lines.Add(svalue);
end;

procedure TForm1.Button3Click(Sender: TObject);
var jsobj, jso : TJsonObject;
    jsa : TJsonArray;
    jsp : TJsonPair;
begin
    jsObj := TJsonObject.Create();
    jsa := TJsonArray.Create();
    jsp := TJSONPair.Create('Array', jsa);
    jsObj.AddPair(jsp);

    jso := TJsonObject.Create();
    jso.AddPair('A1', 'A_1');
    jso.AddPair('A2', 'A_2');
    jsa.AddElement(jso);


    jso := TJsonObject.Create();
    jso.AddPair('B1', 'B_1');
    jso.AddPair('B2', 'B_2');
    jsa.AddElement(jso);

    //Ex :{"Array":[{"A1":"A_1","A2":"A_2"},{"B1":"B_1","B2":"B_2"}]}
end;

end.

沒有留言:

張貼留言