private async Task <T> ParseResponse <T>(HttpResponseMessage response) { if (response == null) { throw new BitPayException("Error: HTTP response is null"); } // Get the response as a dynamic object for detecting possible error(s) or data object. // An error(s) object raises an exception. // A data object has its content extracted (throw away the data wrapper object). String responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false); if (responseString.Length > 0 && responseString[0] == '[') { // some endpoints return an array at the root (like /Ledgers/{currency}). // without short circuiting here, the JObject.Parse will throw return(JsonConvert.DeserializeObject <T>(responseString)); } JObject obj = null; try { obj = JObject.Parse(responseString); } catch { // Probably a http error, send this instead of parsing error. response.EnsureSuccessStatusCode(); throw; } // Check for error response. if (obj.Property("error") != null) { var ex = new BitPayException(); ex.AddError(obj.Property("error").Value.ToString()); throw ex; } if (obj.Property("errors") != null) { var ex = new BitPayException(); foreach (var errorItem in ((JArray)obj.Property("errors").Value).OfType <JObject>()) { ex.AddError(errorItem.Property("error").Value.ToString() + " " + errorItem.Property("param").Value.ToString()); } throw ex; } T data = default(T); // Check for and exclude a "data" object from the response. if (obj.Property("data") != null) { responseString = JObject.Parse(responseString).SelectToken("data").ToString(); data = JsonConvert.DeserializeObject <T>(responseString); } return(data); }
private async Task <T> ParseResponse <T>(HttpResponseMessage response) { if (response == null) { throw new BitPayException("Error: HTTP response is null"); } // Get the response as a dynamic object for detecting possible error(s) or data object. // An error(s) object raises an exception. // A data object has its content extracted (throw away the data wrapper object). String responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false); var obj = JObject.Parse(responseString); // Check for error response. if (obj.Property("error") != null) { var ex = new BitPayException(); ex.AddError(obj.Property("error").Value.ToString()); throw ex; } if (obj.Property("errors") != null) { var ex = new BitPayException(); foreach (var errorItem in ((JArray)obj.Property("errors").Value).OfType <JObject>()) { ex.AddError(errorItem.Property("error").Value.ToString() + " " + errorItem.Property("param").Value.ToString()); } throw ex; } T data = default(T); // Check for and exclude a "data" object from the response. if (obj.Property("data") != null) { responseString = JObject.Parse(responseString).SelectToken("data").ToString(); data = JsonConvert.DeserializeObject <T>(responseString); } return(data); }