Anonymous
Readfromjsonasync не работает для типа строки
Сообщение
Anonymous » 08 июл 2025, 10:39
Я получаю ошибку
, когда я использую тип строки с readfrom yrishsyn. />>
Код: Выделить всё
{
"token_type": "Bearer",
"expires_in": 3599,
"ext_expires_in": 3599,
"access_token": "xyz"
}
< /code>
code: < /p>
private async Task PostAsync(KeyValuePair[] Content, HttpClient Client)
{
using (HttpResponseMessage responseMessage = Client.PostAsync(_requestUri, new FormUrlEncodedContent(Content)).Result)
{
responseMessage.EnsureSuccessStatusCode();
if (typeof(T).FullName == "System.String")
{
return await responseMessage.Content.ReadFromJsonAsync();
}
else
{
return JsonConvert.DeserializeObject(await responseMessage.Content.ReadAsStringAsync());
}
}
}
< /code>
целый код: < /p>
public class IntegrationRestApi {
public readonly IntegrationParameters Parameters;
private readonly IHttpClientFactory _httpFactory;
private static JObject _json;
private HttpMethod _method {
get;
set;
}
private string _HttpJsonSchema {
get;
set;
}
private string _requestUri {
get;
set;
}
private string _host {
get;
set;
}
public IntegrationRestApi(IHttpClientFactory httpClientFactory) {
_httpFactory = httpClientFactory;
Parameters = new IntegrationParameters();
}
public async Task < T > SendAsync < T > (string HttpJsonSchema) {
if (IsValidJson(HttpJsonSchema)) {
_HttpJsonSchema = HttpJsonSchema;
}
Parameters.ToList().ForEach(item => {
_HttpJsonSchema = _HttpJsonSchema.Replace($"{" {
" + item.Key + "
}
"}", item.Value);
});
_json = JObject.Parse(_HttpJsonSchema);
_method = new HttpMethod(_json.Value < string > ("method").ToString());
_requestUri = _json.Value < string > ("url").ToString();
_host = _json.Value < string > ("host");
var jsonHeaders = "[" + _json["headers"].ToString() + "]";
using(HttpClient client = _httpFactory.CreateClient()) {
foreach(var header in JArray.Parse(jsonHeaders).Children < JObject > ()) {
foreach(JProperty parsedProperty in header.Properties()) {
client.DefaultRequestHeaders.Add(parsedProperty.Name, parsedProperty.Value.ToString());
}
}
client.BaseAddress = new Uri(_host);
try {
var jsonParameters = "[" + _json["query_parameters"].ToString() + "]";
var prm = JArray.Parse(jsonParameters).Children < JObject > ().FirstOrDefault();
if (_method == HttpMethod.Post) {
var replaceContent = (from x in prm.Properties().AsEnumerable() select new KeyValuePair < string, string > (x.Name, x.Value.ToString())).ToArray();
return await PostAsync < T > (replaceContent, client);
} else if (_method == HttpMethod.Get) {
var replaceContent = (from x in prm.Properties().AsEnumerable() select new string(string.Concat(x.Name, "=", x.Value.ToString()))).ToArray();
var queryString = string.Join("&", replaceContent);
return await GetAsync < T > (queryString, client);
} else
throw new ArgumentException("Method.Is.Not.Found");
} catch (Exception ex) {
throw;
} finally {
client.Dispose();
}
}
}
private static bool IsValidJson(string strInput) {
if (string.IsNullOrWhiteSpace(strInput)) {
return false;
}
strInput = strInput.Trim();
if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object
(strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array
{
try {
var obj = JToken.Parse(strInput);
return true;
} catch (JsonReaderException jex) {
return false;
} catch (Exception ex) //some other exception
{
return false;
}
} else {
return false;
}
}
private async Task < T > PostAsync < T > (KeyValuePair < string, string > [] Content, HttpClient Client) {
using(HttpResponseMessage responseMessage = Client.PostAsync(_requestUri, new FormUrlEncodedContent(Content)).Result) {
responseMessage.EnsureSuccessStatusCode();
if (typeof (T) == typeof (string)) {
return await responseMessage.Content.ReadFromJsonAsync < T > ();
} else {
return JsonConvert.DeserializeObject < T > (await responseMessage.Content.ReadAsStringAsync());
}
}
}
private async Task < T > GetAsync < T > (string QueryString, HttpClient Client) {
_requestUri = $ "{_requestUri}/{QueryString}";
using(HttpResponseMessage responseMessage = Client.GetAsync(_requestUri).Result) {
responseMessage.EnsureSuccessStatusCode();
if (typeof (T).FullName == "System.String") {
return await responseMessage.Content.ReadFromJsonAsync < T > ();
} else {
return JsonConvert.DeserializeObject < T > (await responseMessage.Content.ReadAsStringAsync());
}
}
}
}
Мы будем признателен за вашу помощь.
Подробнее здесь:
https://stackoverflow.com/questions/796 ... tring-type
1751960388
Anonymous
Я получаю ошибку , когда я использую тип строки с readfrom yrishsyn. />>[code]{ "token_type": "Bearer", "expires_in": 3599, "ext_expires_in": 3599, "access_token": "xyz" } < /code> code: < /p> private async Task PostAsync(KeyValuePair[] Content, HttpClient Client) { using (HttpResponseMessage responseMessage = Client.PostAsync(_requestUri, new FormUrlEncodedContent(Content)).Result) { responseMessage.EnsureSuccessStatusCode(); if (typeof(T).FullName == "System.String") { return await responseMessage.Content.ReadFromJsonAsync(); } else { return JsonConvert.DeserializeObject(await responseMessage.Content.ReadAsStringAsync()); } } } < /code> целый код: < /p> public class IntegrationRestApi { public readonly IntegrationParameters Parameters; private readonly IHttpClientFactory _httpFactory; private static JObject _json; private HttpMethod _method { get; set; } private string _HttpJsonSchema { get; set; } private string _requestUri { get; set; } private string _host { get; set; } public IntegrationRestApi(IHttpClientFactory httpClientFactory) { _httpFactory = httpClientFactory; Parameters = new IntegrationParameters(); } public async Task < T > SendAsync < T > (string HttpJsonSchema) { if (IsValidJson(HttpJsonSchema)) { _HttpJsonSchema = HttpJsonSchema; } Parameters.ToList().ForEach(item => { _HttpJsonSchema = _HttpJsonSchema.Replace($"{" { " + item.Key + " } "}", item.Value); }); _json = JObject.Parse(_HttpJsonSchema); _method = new HttpMethod(_json.Value < string > ("method").ToString()); _requestUri = _json.Value < string > ("url").ToString(); _host = _json.Value < string > ("host"); var jsonHeaders = "[" + _json["headers"].ToString() + "]"; using(HttpClient client = _httpFactory.CreateClient()) { foreach(var header in JArray.Parse(jsonHeaders).Children < JObject > ()) { foreach(JProperty parsedProperty in header.Properties()) { client.DefaultRequestHeaders.Add(parsedProperty.Name, parsedProperty.Value.ToString()); } } client.BaseAddress = new Uri(_host); try { var jsonParameters = "[" + _json["query_parameters"].ToString() + "]"; var prm = JArray.Parse(jsonParameters).Children < JObject > ().FirstOrDefault(); if (_method == HttpMethod.Post) { var replaceContent = (from x in prm.Properties().AsEnumerable() select new KeyValuePair < string, string > (x.Name, x.Value.ToString())).ToArray(); return await PostAsync < T > (replaceContent, client); } else if (_method == HttpMethod.Get) { var replaceContent = (from x in prm.Properties().AsEnumerable() select new string(string.Concat(x.Name, "=", x.Value.ToString()))).ToArray(); var queryString = string.Join("&", replaceContent); return await GetAsync < T > (queryString, client); } else throw new ArgumentException("Method.Is.Not.Found"); } catch (Exception ex) { throw; } finally { client.Dispose(); } } } private static bool IsValidJson(string strInput) { if (string.IsNullOrWhiteSpace(strInput)) { return false; } strInput = strInput.Trim(); if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object (strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array { try { var obj = JToken.Parse(strInput); return true; } catch (JsonReaderException jex) { return false; } catch (Exception ex) //some other exception { return false; } } else { return false; } } private async Task < T > PostAsync < T > (KeyValuePair < string, string > [] Content, HttpClient Client) { using(HttpResponseMessage responseMessage = Client.PostAsync(_requestUri, new FormUrlEncodedContent(Content)).Result) { responseMessage.EnsureSuccessStatusCode(); if (typeof (T) == typeof (string)) { return await responseMessage.Content.ReadFromJsonAsync < T > (); } else { return JsonConvert.DeserializeObject < T > (await responseMessage.Content.ReadAsStringAsync()); } } } private async Task < T > GetAsync < T > (string QueryString, HttpClient Client) { _requestUri = $ "{_requestUri}/{QueryString}"; using(HttpResponseMessage responseMessage = Client.GetAsync(_requestUri).Result) { responseMessage.EnsureSuccessStatusCode(); if (typeof (T).FullName == "System.String") { return await responseMessage.Content.ReadFromJsonAsync < T > (); } else { return JsonConvert.DeserializeObject < T > (await responseMessage.Content.ReadAsStringAsync()); } } } [/code] } Мы будем признателен за вашу помощь. Подробнее здесь: [url]https://stackoverflow.com/questions/79680865/readfromjsonasync-is-not-working-for-string-type[/url]