2017/03/23

DIY 修正 JSON.ToString 的處理

你在 JSON 的轉碼上也遇到問題了嗎?


在 Delphi 初期支援 JSON 版本,JSON相關類別有個【ToString】的函式,對於異質平台間的轉換需求上,替我們省下了不少時間。

But!人生最重要的就是這個 But!


實際在與 JavaScript 做轉換時,卻發生 JavaScript Parse 失敗的情形。

不查不知道,一查才驚到:




























這是, BUG FEATURES 啊!

JSON Class 的 ToString 函式就單純只做引號【"】處理,其它就垃圾進垃圾出。
而在 XE7 之後,多了個 ToJSON 方法,docwiki 對於它們兩個的差異是這麼寫的:

ToJSON: Returns the string representation of this JSON object.
ToString: Serializes the current JSON string value into a quoted string.


XE - XE6 的開發者也別傷心,JSON Class 有提供 ToBytes 方法,可以轉換 U+0020-U+007F 以外的特殊字元,我們也可以得到轉換 7-bit 字元後的字串。

於是我們可以整理上述內容後,使用 class helper 完成合併 JSON 物件方法,以下是程式碼:


  TJsonAncestorHelper = class helper for TJsonAncestor
  public
    function ToStringEx(): string;
  end;

{ TJsonAncestorHelper }

function TJsonAncestorHelper.ToStringEx: string;
var
  bytes: TBytes;
  len: Integer;
begin
  {$IF CompilerVersion > 27}
    Result := Self.ToJson;
  {$ELSE}
    SetLength(bytes, Self.EstimatedByteSize);
    len := Self.ToBytes(bytes, 0);
    {$IF CompilerVersion > 22 }
    Result := TEncoding.ANSI.GetString(bytes, 0, len);
    {$ELSE}
    Result := TEncoding.ASCII.GetString(bytes, 0, len);
    {$IFEND}
  {$IFEND}
end;

在之後的異質平台處理,我們又少了一個障礙!

See also:

Photo Source: here.

沒有留言:

張貼留言