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

  • 相关阅读:
    FreeModbus TCP
    C#之用户自定义控件
    使用C库制作DLL
    C# Unable to load DLL 'WzCanDll.dll':找不到指定的模块
    C#之改变窗体icon图标、新建类文件、调用dll库
    sim800c GPRS模块的透传模式
    STM32上使用JSON
    STM32之串口IAP更新升级
    Fortran语言的REWIND和BACKSPACE 函数
    Code blocks 编译Fortran(转载)
  • 原文地址:https://www.cnblogs.com/kinglandsoft/p/9342750.html
Copyright © 2011-2022 走看看