红鱼儿

TJson.format() 输出错误的CRLF

 下面的JSON串:

{
 "a":"x=\"a,b\""
} 

通过下面代码输出,多了CRLF:

procedure JsonFormatTest;
var jo:TJsonObject;
    j:TJson;
begin
    jo := TJsonObject.Create;
    jo.AddPair('a', 'x="a,b"');
 
    j := TJson.Create;
    ShowMessage( j.Format(jo) );
end;

变成这样:

{
    "a":"x=\"a,
     b\""
}

下面是修正方法:

unit MM.Helpers.REST.Json;
 
interface
 
uses
  System.Types, System.JSON, REST.Json;
 
type
  TJsonHelper = class helper for TJson
  public
    class function HFormat(AJsonValue: TJsonValue): string;
  end;
 
 
implementation
 
{ TJsonHelper }
 
class function TJsonHelper.HFormat(AJsonValue: TJsonValue): string;
var
  s: string;
  c: char;
  EOL: string;
  INDENT: string;
  LIndent: string;
  isEOL: boolean;
  isInString: boolean;
  isEscape: boolean;
begin
  Result := '';
  EOL := sLineBreak; // kanteruk: use platform line brake
  INDENT := '  ';
  isEOL := true;
  isInString := false;
  isEscape := false;
  s := AJsonValue.ToJSON; // kanteruk: fix here
  for c in s do
  begin
    if not isInString and ((c = '{') or (c = '[')) then
    begin
      if not isEOL then
        Result := Result + EOL;
      Result := Result + LIndent + c + EOL;
      LIndent := LIndent + INDENT;
      Result := Result + LIndent;
      isEOL := true;
    end
    else if not isInString and (c = ',') then
    begin
      isEOL := false;
      Result := Result + c + EOL + LIndent;
    end
    else if not isInString and ((c = '}') or (c = ']')) then
    begin
      Delete(LIndent, 1, Length(INDENT));
      if not isEOL then
        Result := Result + EOL;
      Result := Result + LIndent + c + EOL;
      isEOL := true;
    end
    else
    begin
      isEOL := false;
      Result := Result + c;
    end;
    if not isEscape and (c = '"') then
      isInString := not isInString;
    isEscape := (c = '\') and not isEscape; // kanteruk: fix here, move this line down
  end;
end;
 
end.

Delphi 10.2.3,官方QC地址:https://quality.embarcadero.com/browse/RSP-20404

Delphi 10.3解决了!

 

posted on 2018-07-20 22:24  红鱼儿  阅读(533)  评论(0编辑  收藏  举报