我有这种通用方法,用于执行 Post 请求,然后解析这样的响应。
private async Task<object> PostAsync<T1,T2>(string uri, T2 content)
{
using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, uri))
{
var json = JsonConvert.SerializeObject(content);
using (var stringContent = new StringContent(json, Encoding.UTF8, "application/json"))
{
requestMessage.Content = stringContent;
HttpResponseMessage response = await _client.SendAsync(requestMessage);
if (response.IsSuccessStatusCode)
{
_logger.LogInformation("Request Succeeded");
T1 responseModel = JsonConvert.DeserializeObject<T1>(await response.Content.ReadAsStringAsync());
return responseModel;
}
else
{
return await GetFailureResponseModel(response);
}
}
}
}
现在的问题是,某些发帖请求响应位于 SnakeCase 中,而其他发于 CamelCase 中。我该如何解决此问题。
答案 0 :(得分:2)
鉴于在编译时就知道了snake_case以及需要默认策略时,您可以这样做:
import matplotlib.pyplot as plt
import numpy as np
data = np.random.random(size=100)
f, a = plt.subplots(2, 2, figsize=(10, 5), constrained_layout=True)
a[0,0].plot(data)
a[0,0].set_title("this is a really long title\n"*2)
a[0,1].plot(data)
a[1,1].plot(data)
plt.suptitle("a big long suptitle that runs into the title\n"*2);
因此,当您需要默认策略时:
private Task<object> PostAsync<T1, T2>(string uri, T2 content)
{
return PostAsync<T1, T2>(uri, content, new DefaultNamingStrategy());
}
private async Task<object> PostAsync<T1, T2>(string uri, T2 content, NamingStragy namingStrategy)
{
using (var requestMessage = new HttpRequestMessage(HttpMethod.Post, uri))
{
var json = JsonConvert.SerializeObject(content);
using (var stringContent = new StringContent(json, Encoding.UTF8, "application/json"))
{
requestMessage.Content = stringContent;
HttpResponseMessage response = await _client.SendAsync(requestMessage);
if (response.IsSuccessStatusCode)
{
_logger.LogInformation("Request Succeeded");
var deserializerSettings = new JsonSerializerSettings
{
ContractResolver = new DefaultContractResolver
{
NamingStrategy = namingStrategy
}
};
T1 responseModel = JsonConvert.DeserializeObject<T1>(await response.Content.ReadAsStringAsync(), deserializerSettings);
return responseModel;
}
else
{
return await GetFailureResponseModel(response);
}
}
}
}
,并且,当您需要snake_case时:
await PostAsync<Some1, Some2>(uri, some2Content);