通用方法Json解析

问题描述 投票:1回答:1

我有这个泛型方法,用于执行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);

            }
        }
    }
}

现在问题是一些Post请求响应在SnakeCase中,而其他一些在CamelCase中。我该如何解决这个问题。

c# json asp.net-core
1个回答
2
投票

鉴于您在编译时知道snake_case并且需要默认策略时,您可以这样做:

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);

            }
        }
    }
}

因此,当您需要默认策略时:

await PostAsync<Some1, Some2>(uri, some2Content);

而且,当你需要snake_case时:

await PostAsync<Some1, Some2>(uri, some2Content, new SnakeCaseNamingStrategy());