2017/06/26

JSON Parse in Delphi XE (01)

在 Delphi.ktop 的主題中,看到了【JSON求教】這一篇

如果在 XE 裡面要實現,是不是也是這麼簡單?

想到了,就開始來實作吧!


首先是 Download 的部份:
procedure TForm1.Button1Click(Sender: TObject);
var
  ss: string;
  ssm: TStringStream;
begin
  Memo1.Clear;
  ssm := TStringStream.Create('', TEncoding.UTF8);
  ss := IdHTTP1.Get('https://blockchain.info/ticker');
  IdHTTP1.Get('https://blockchain.info/ticker', ssm);
  Memo1.Lines.Add(ssm.DataString);
  ssm.Free;
end;

接著是 JSON Parse 的部份:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
procedure TForm1.Button2Click(Sender: TObject);
var
  LJSObj, LJSSubObj: TJSONObject;
  LJSPair: TJSONPair;
  LJSVal: TJSONValue;
  LPos01: Integer;
  LStr: string;
begin
  LJSObj := TJSONObject.ParseJSONValueUTF8(TEncoding.UTF8.GetBytes(Memo1.Text), 0) as TJSONObject;
  Memo1.Clear;
  if LJSObj <> nil then
  begin
    for LPos01 := 0 to LJSObj.Size-1 do
    begin
      try
        LJSPair := LJSObj.Get(LPos01);
        LJSSubObj := LJSPair.JsonValue as TJSONObject;
        LStr := LJSSubObj.Get('15m').JsonValue.Value;
        Memo1.Lines.Add(LJSSubObj.Get('15m').JsonValue.Value);
        Memo1.Lines.Add(LJSSubObj.Get('last').JsonValue.Value);
        Memo1.Lines.Add(LJSSubObj.Get('buy').JsonValue.Value);
        Memo1.Lines.Add(LJSSubObj.Get('sell').JsonValue.Value);
        Memo1.Lines.Add(LJSSubObj.Get('symbol').JsonValue.Value);
      except
        on E: Exception do
        begin
          Memo1.Lines.Add('Error: '+LJSSubObj.ToString);
          Exit;
        end;
      end;
    end;
  end;
end;

和前版的 Delphi 有很大的落差,畢竟新版擴充的更加完美,但現階段仍然可以解決解析的問題。


於是我們就得到了以下的內容:
解析後的結果

 得到了一個例外,看來是 UNICODE 的問題,到底該怎麼解呢?

欲知詳情,我們下回待續!

沒有留言:

張貼留言