StringToJSONString

StringToJSONString

function StringToJSONString(const S: string; strict: Boolean = False): string;
var
  I, J, L: Integer;
  P: PChar;
  C: Char;
begin
  I := 1;
  J := 1;
  Result := '';
  L := Length(S);
  P := PChar(S);
  while I <= L do
  begin
    C := Char(P^);
    Result := Result + Copy(S, J, I - J);
    if (C in ['a'..'z']) or (C in ['A'..'Z']) or (C in ['0'..'9']) or (C = ':')
      or (c='{') or (c='}') or (c='"') or (c='[') or (c=']') or (c=','
      ) then
      Result := Result + C
    else
    case C of
      '\':
        Result := Result + '\\';
      '/':
        if strict then
          Result := Result + '\/'
        else
          Result := Result + '/';
      #8:  //退格
        Result := Result + '\b';
      #9:  //水平定位符号
        Result := Result + '\t';
      #10: //换行键
        Result := Result + '\n';
      #12: //换页键
        Result := Result + '\f';
      #13: //回车
        Result := Result + '\r';
    else  //汉字
      Result := Result + '\u' + IntToHex(Ord(C), 4);
    end;
    J := I + 1;
    Inc(I);
    Inc(P);
  end;
  Result := Result + Copy(S, J, I - 1);
end;

 

function JSONStringToString(const S: string): string;
var
  I, J, L: Integer;
  P: PChar;
  w: string;
begin
  I := 1;
  J := 1;
  L := Length(S);
  Result := '';
  P := PChar(S);
  while (I <= L) do
  begin
    if (P^ = '\') then
    begin
      Result := Result + Copy(S, J, I - J);
      Inc(P);
      if (P^ <> #0) then
      begin
        Inc(I);
        case Char(P^) of
          '\', '"', '/':
            Result := Result + P^;
          'b':
            Result := Result + #8;
          't':
            Result := Result + #9;
          'n':
            Result := Result + #10;
          'f':
            Result := Result + #12;
          'r':
            Result := Result + #13;
          'u':
            begin
              w := Copy(S, I + 1, 4);
              Inc(I, 4);
              Inc(P, 4);
              Result := Result + Char(StrToInt('$' + w));
            end;
        end;
      end;
      J := I + 1;
    end;
    Inc(I);
    Inc(P);
  end;
  Result := Result + Copy(S, J, I - J + 1);
end;

  

 

procedure TForm1.Button1Click(Sender: TObject);
begin
  var s: string;
  s := StringToJSONString('{"Key1":"张三"}');
  memo2.Lines.Add(s);  //{"Key1":"\u5F20\u4E09"}
  s := JSONStringToString(s);  //{"Key1":"张三"}
  memo2.Lines.Add(s);
end;

  

  

posted @ 2020-12-01 10:21  delphi中间件  阅读(531)  评论(0编辑  收藏  举报