zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    Django01
    WEB框架介绍
    前端插件介绍
    JQuery
    DOM
    js
    css
    HTML
    图片懒加载
    js中style,currentStyle和getComputedStyle的区别
  • 原文地址:https://www.cnblogs.com/kinglandsoft/p/9342750.html
Copyright © 2011-2022 走看看