/// <summary> /// Read the response as a JSON string & deserialize /// </summary> public TContent GetBodyAsJson <TContent>() where TContent : class { TContent result = null; // if we got a valid memory stream if ((this.MemStream != null) // not empty && (this.MemStream.Length > 0)) { try { // reset stream position this.MemStream.Position = 0; // deserialize result = SerializerForJson.Deserialize <TContent>(this.MemStream); // if none if (result == null) { // add an error this.AddErrorMessage("Unexpected result : response has a body, JSON deserialization did not fail, but no content has been deserialized"); } } catch (Exception exc) { // add an error this.AddErrorMessage("Could not deserialize response body as JSON - " + exc); } } return(result); }
/// <summary> /// Send the request, given content is serialized in JSON into the request body /// </summary> public ResponseEx SendAsJson <TContent>(TContent content = null, int?timeout = null) where TContent : class { ResponseEx result = null; // prepare the request and force JSON string errorMessage; var request = InnerPrepareRequest(new ContentType("application/json"), timeout, (content != null), out errorMessage); // if we have a request if ((request != null) // and no error message && string.IsNullOrEmpty(errorMessage)) { // if we got a content if (content != null) { // get the encoding var encoding = (this._encoding ?? EncodingDefault); // open the stream using (var stream = request.GetRequestStream()) { // serialize if (!SerializerForJson.Serialize(stream, content, encoding)) { // if serialization failed errorMessage = "JSON serialization failed"; } } } } // if we have a request if ((request != null) // and no error message && string.IsNullOrEmpty(errorMessage)) { // then send the request and get the response result = ResponseEx.SendRequest(request); } // if we had an error at some point else { // then this is a failure result = ResponseEx.Failure(this._url, errorMessage); } return(result); }