unit PM.JSON; interface uses System.SysUtils, System.Classes, System.JSON, IdCustomHTTPServer; type TJSONHelper = class public class function ReadBody(ARequest: TIdHTTPRequestInfo): TJSONObject; class procedure SendJSON(AResponse: TIdHTTPResponseInfo; AObj: TJSONValue; ACode: Integer = 200; AOwnsObj: Boolean = True); class procedure SendError(AResponse: TIdHTTPResponseInfo; ACode: Integer; const AMsg: string); class procedure SendOK(AResponse: TIdHTTPResponseInfo; const AMessage: string = 'OK'); end; implementation class function TJSONHelper.ReadBody(ARequest: TIdHTTPRequestInfo): TJSONObject; var S: string; LSS: TStringStream; LValue: TJSONValue; begin if ARequest.PostStream = nil then Exit(TJSONObject.Create); LSS := TStringStream.Create('', TEncoding.UTF8); try ARequest.PostStream.Position := 0; LSS.CopyFrom(ARequest.PostStream); S := LSS.DataString; finally LSS.Free; end; if Trim(S) = '' then Exit(TJSONObject.Create); LValue := TJSONObject.ParseJSONValue(S); if LValue is TJSONObject then Result := TJSONObject(LValue) else begin LValue.Free; Result := TJSONObject.Create; end; end; class procedure TJSONHelper.SendJSON(AResponse: TIdHTTPResponseInfo; AObj: TJSONValue; ACode: Integer; AOwnsObj: Boolean); begin AResponse.ResponseNo := ACode; AResponse.ContentType := 'application/json; charset=utf-8'; AResponse.CharSet := 'utf-8'; AResponse.ContentText := AObj.ToJSON; if AOwnsObj then AObj.Free; end; class procedure TJSONHelper.SendError(AResponse: TIdHTTPResponseInfo; ACode: Integer; const AMsg: string); var LObj: TJSONObject; begin LObj := TJSONObject.Create; LObj.AddPair('error', AMsg); SendJSON(AResponse, LObj, ACode); end; class procedure TJSONHelper.SendOK(AResponse: TIdHTTPResponseInfo; const AMessage: string); var LObj: TJSONObject; begin LObj := TJSONObject.Create; LObj.AddPair('message', AMessage); SendJSON(AResponse, LObj); end; end.